java - 了解 ExecutorService 何时结束

标签 java multithreading

我正在尝试使用 ExecutorServiceBlockingQueue<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.setDaemon(true) :

Thread t = new Thread(new Runnable() {
  //...
});
t.setDaemon(true);
t.start();

现在,当 ExecutorService 中的所有线程在关闭后终止时,main 线程也会终止,JVM 将停止,因为您唯一剩下的线程是守护进程。

关于java - 了解 ExecutorService 何时结束,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14287195/

相关文章:

java - 多线程套接字服务器通过消息关闭Java

android - 你如何让一个线程运行它的内容,暂停并重复?

java - 我不明白这段代码

java - 关于try/catch block 中变量范围的问题

java - Java中linkedList实现的删除方法

java - 将@Value注入(inject)到导入的第三个jar中的bean中

java - Android:方法中包含的中断线程

WCF 命名管道服务设置

python - Pyqt5多线程错误:QObject::connect:无法对类型 'QTextCursor'的参数进行排队

java - java main方法的执行创建了多少个线程?