java8 线程 怎么退出,如何在Java 8中使用CompletableFuture启动异步任务并使主线程完成并退出...

I have the following code (more or less):

ExecutorService executor = Executors.newFixedThreadPool(10);

CompletableFuture

.supplyAsync(()->{

return longRunningMethodThatReturnsBoolean();

}, executor)

.thenAcceptAsync(taskResult -> {

logResult();

executor.shutdown();

}, executor);

This allows the code in the main thread to continue, however I was expecting the main thread to die when it finished and the future to keep working in it's own thread, but the main thread stays alive until the CompletableFuture finishes even though the main thread isn't doing anything anymore.

I'm kind of new to this, am I missing something? Is it even possible?

Any help will be greatly appreciated!!!

解决方案

Actually, if your main thread doesn't wait on the CompletableFuture's .get() or any other blocking method, then it dies as soon as it reaches the end of the main method.

You can check it using the following example:

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);

}

The exit method of class Runtime has been called and the security manager has permitted the exit operation to take place.

All threads that are not daemon threads have died, either by returning from the call to the run method or by throwing an exception

that propagates beyond the run method.

It means that even though the main thread is dead, the virtual machine continues to work because all threads created by the Executors.newFixedThreadPool(10) are non-daemon. You can read about it in the documentation of the defaultThreadFactory() method in the Executors class:

Each new thread is created as a non-daemon thread with priority set to

the smaller of Thread.NORM_PRIORITY and the maximum priority permitted

in the thread group

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值