我正在尝试使用 ExecutorService
与 BlockingQueue<Runnable>
但我在退出脚本时遇到问题。它顺利完成,但我不知道会继续等待。
首先我有一个类
public class GenericTask implements Runnable {
public void run() {
// do stuff
}
}
然后是代码
BlockingQueue<Runnable> queue = new ArrayBlockingQueue<Runnable>(10000, true);
ExecutorService myExecutor = Executors.newFixedThreadPool(numThreads);
new Thread(new Runnable() {
public void run() {
for (; ; ) {
try {
myExecutor.execute(queue.take());
} catch (InterruptedException ignored) {
}
}
}
}).start();
while (...) {
queue.put(new GenericTask());
}
int waitTime = 500;
myExecutor.shutdown();
try {
while (!myExecutor.awaitTermination(waitTime, TimeUnit.MILLISECONDS)) {
logger.info("Waiting...");
Thread.sleep(waitTime);
}
} catch (Exception e) {
e.printStackTrace();
}
System.out.println("Finished!");
当它打印“Finished!”时,它真的完成了,但脚本继续进行,除非我添加 System.exit(0)
,但我认为这是不正确的。
最佳答案
最后,您正确地关闭了线程池中的所有线程。但是还有另一个非守护线程阻止 JVM 终止。你能发现吗?这是您的匿名生产者线程,内部有无限循环:for (;;)
。
Thread t = new Thread(new Runnable() {
//...
});
t.setDaemon(true);
t.start();
现在,当 ExecutorService
中的所有线程在关闭后终止时,main
线程也会终止,JVM 将停止,因为您唯一剩下的线程是守护进程。
关于java - 了解 ExecutorService 何时结束,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14287195/