我正在使用java中的一些低级多线程,其中我有两个方法:产生和消费:
public class Producer {
private LinkedList<Integer> list = new LinkedList();
private final int LIMIT = 10;
private Object lock = new Object();
public void produce() throws InterruptedException {
int value = 0;
while (true) {
synchronized (lock) {
// while loopet er til, for at blive ved med at tjekke at tjekke, at listen er fuld
while (list.size() == LIMIT) {
//notify vækker dette while-loop
lock.wait(); //låsen venter indtil der er plads til at blive taget en ny værdi ud
System.out.println("hej");
}
list.add(value++);
lock.notify();
}
}
}
public void consume() throws InterruptedException {
Random random = new Random();
while (true) {
synchronized (lock) {
while (list.size() == 0) {
lock.wait();
}
System.out.print("list size is " + list.size());
int value = list.removeFirst();
System.out.println("Current value is " + value);
lock.notify();
}
Thread.sleep(random.nextInt(1000));
}
}
}我可以在main方法中放入什么让线程运行?因为我没有使用Runnable接口的Thread,所以我不能启动它们,并且实例化一个对象,调用这些方法是不起作用的?
发布于 2018-08-28 04:36:01
你可以使用匿名线程来做这件事。
public static void main(String args[]) throws IOException, SaxonApiException {
Producer producer = new Producer();
new Thread()
{
public void run() {
try {
producer.consume();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}.start();
new Thread()
{
public void run() {
try {
producer.produce();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}.start();
}我在输出中得到的结果是这样的。
list size is 1Current value is 0
list size is 10Current value is 1
hej
list size is 10Current value is 2
hej
list size is 10Current value is 3
hej
list size is 10Current value is 4
hej发布于 2018-08-28 11:13:45
我假设这两个方法都在类生成器中。不需要其他类。
public static void main(String... args) {
Producer producer = new Producer();
Thread t1 = new Thread(producer::produce);
Thread t2 = new Thread(producer::consume);
t1.start(); t2.start();
}但是首先必须从produce和consume方法的签名中删除throws InterruptedException。从线程的根方法抛出异常是没有意义的,因为没有调用者可以捕获并响应该异常。只需捕获方法内部的异常,打印stacktrace并返回即可。
发布于 2018-08-28 04:33:46
为了能够同时运行你的方法,你需要实现线程类/ runnable抽象的一些变体,如下所示:
// Thread variant
class MultithreadingObject extends Thread{
public void run(){
print("...");
}
}
public static void main(string[] args){
threadOne = new MultithreadingObject();
threadTwo = new MultithreadingObject();
// Run both threads
threadOne.start();
threadTwo.start();
}实现Runnable变体:
public class MyThread extends Thread {
public MyThread() {
super("MyThread");
}
public void run() {
//Code
}
}
public static void main(string[] args){
threadOne = new MyThread();
threadTwo = new MyThread();
// Run both threads
threadOne.start();
threadTwo.start();
}https://stackoverflow.com/questions/52046419
复制相似问题