gpt4 book ai didi

java - 无法在另一个线程之后启动执行程序

转载 作者:行者123 更新时间:2023-12-01 19:57:48 26 4
gpt4 key购买 nike

当我运行下面的代码时,生产者 run() 方法启动并将随机数放入作业队列,但消费者 run() 方法从未运行。这里的主要问题是什么?

这是主类;

public static LinkedBlockingQueue<Integer> jobs = new LinkedBlockingQueue<>();

public static void main(){

MessageProducer producer = new MessageProducer(jobs);
Thread producerThread = new Thread(producer);
producerThread.run();

MessageConsumer consumer = new MessageConsumer(jobs);
Executor executor = Executors.newFixedThreadPool(3);
executor.execute(consumer);

}

制片人;

public class MessageProducer implements Runnable {

public LinkedBlockingQueue<Integer> jobs;

public MessageProducer(LinkedBlockingQueue<Integer> jobs){
this.jobs = jobs;
}

@Override
public void run() {
while(true) {
try {
jobs.put((int) (Math.random() * 10));
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}

消费者;

public class MessageConsumer implements Runnable{

public LinkedBlockingQueue<Integer> jobs;

public MessageConsumer(LinkedBlockingQueue<Integer> jobs) {
this.jobs = jobs;
}


@Override
public void run() {
while(true) {
System.out.println("Executing " + jobs.poll());
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}

最佳答案

不要调用Thread.run() 。它不会启动线程。它调用run()在您的情况下是无限循环的方法。
因此 JVM 停留在 producerThread.run();永远不会回来。

而是调用Thread.start()将负责调用 run()方法。

Thread.start() javadoc 确实指出:

Causes this thread to begin execution; the Java Virtual Machine calls the run method of this thread.

关于java - 无法在另一个线程之后启动执行程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48930063/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com