我正在尝试使用ExecutorService
withBlockingQueue<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!");
当它打印“完成!”时,它真的完成了,但是除非我添加一个,否则脚本会继续进行System.exit(0)
,但我认为这是不正确的。