在Java中,使用java.util.concurrent.ExecutorService
创建的newFixedThreadPool
,如果我在未先使用awaitTermination
的情况下使用shutdown
,则看来主线程将等待直到发生超时。我曾期望awaitTermination
仅等待实际线程完成。为什么?
我已阅读文档: https://docs.oracle.com/javase/7/docs/api/java/util/concurrent/Executors.html https://docs.oracle.com/javase/7/docs/api/java/util/concurrent/ExecutorService.html
和问题: Reason for calling shutdown() on ExecutorService
答案: https://stackoverflow.com/a/50091038/10816178 据说
由于ExecutorService中的线程可能是非守护程序线程, 它们可能会阻止正常的应用程序终止。
在执行者文档中,它说:
在显式关闭之前,池中的线程将一直存在。
但是,我的代码示例未提交任何线程。
我知道我缺少和/或误解了一些东西。
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
public class ExecutorServiceQuestionDemo {
public static void demo() throws InterruptedException {
int numberOfThreads = 3; // for example
long timeoutMinutes = 10;
System.out.println("Started");
ExecutorService executorService = Executors.newFixedThreadPool(numberOfThreads);
//executorService.shutdown();
boolean finishedBeforeTimeout = executorService.awaitTermination(timeoutMinutes, TimeUnit.MINUTES);
System.out.println("Ended, finishedBeforeTimeout = " + finishedBeforeTimeout);
}
public static void main(String[] args) throws InterruptedException{
demo();
}
}