我有以下代码(或多或少):
ExecutorService executor = Executors.newFixedThreadPool(10);
CompletableFuture
.supplyAsync(()->{
return longRunningMethodThatReturnsBoolean();
}, executor)
.thenAcceptAsync(taskResult -> {
logResult();
executor.shutdown();
}, executor);
这允许主线程中的代码继续执行,但是我希望主线程在完成后会终止,而 future 继续在它自己的线程中工作,但主线程保持活动状态,直到 CompletableFuture 完成,即使主线程不在不再做任何事了
我对此有点陌生,我错过了什么吗?有可能吗?
任何帮助将不胜感激!!!
实际上,如果你的主线程不等待CompletableFuture
's .get()
或任何其他阻塞方法,那么它一旦到达末尾就会死亡main
方法。
您可以使用以下示例进行检查:
public static void main(String[] args){
final Thread mainThread = Thread.currentThread();
ExecutorService executor = Executors.newFixedThreadPool(10);
CompletableFuture
.supplyAsync(()-> {
try {
Thread.sleep(1000);
//prints false
System.out.println("Main thread is alive: " + mainThread.isAlive());
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
return true;
}, executor)
.thenAcceptAsync(taskResult -> {
System.out.println("LongRunning is finished");
executor.shutdown();
}, executor);
}
But the Java虚拟机继续执行线程,直到发生以下任一情况
- Runtime 类的 exit 方法已被调用,并且安全管理器已允许进行退出操作。
- 所有线程不是守护进程线程已死亡,要么是通过从 run 方法的调用返回,要么是抛出异常
传播到 run 方法之外。
这意味着即使主线程死了,虚拟机仍然继续工作,因为由主线程创建的所有线程Executors.newFixedThreadPool(10)
are 非守护进程。您可以在文档 of the defaultThreadFactory()
方法中的Executors
class:
每个新线程都被创建为非守护线程,其优先级设置为
Thread.NORM_PRIORITY 和允许的最大优先级中较小的一个
在线程组中
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)