我正在运行 java8 应用程序,看起来一旦主线程退出,进程就会退出。
我正在使用 completableFuture 启动异步任务,如下所示
CompletableFuture cf = CompletableFuture.supplyAsync(() -> task.call());
cf.thenRunAsync(() -> {
try {
System.out.println(Thread.currentThread());
System.out.println((Double)cf.get() * 4.0);
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
});
我希望异步将作为一个单独的线程运行,因此主线程退出不应导致进程退出,但事实并非如此。
我猜异步作业是作为守护线程运行的吗?但无法确认。
最佳答案
如前所述here :
the method
supplyAsync
useForkJoinPool.commonPool()
threadpool which is shared among allCompletableFutures
.
如前所述here
ForkJoinPool
uses threads in daemon mode, there is typically no need to explicitly shutdown such a pool upon program exit.
看来确实如此。
为避免这种情况,您需要传递一个明确的执行程序,例如:
ExecutorService pool = Executors.newFixedThreadPool(5);
final CompletableFuture<String> future = CompletableFuture.supplyAsync(() -> {
... }, pool);
关于java - 退出的主线程会杀死异步任务吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43816328/