繁体   English   中英

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

[英]How to use CompletableFuture in java 8 to start an async task and let main thread finish and exit

我有以下代码(或多或少):

ExecutorService executor = Executors.newFixedThreadPool(10);
CompletableFuture
    .supplyAsync(()->{
        return longRunningMethodThatReturnsBoolean();
    }, executor)
    .thenAcceptAsync(taskResult -> {
        logResult();
        executor.shutdown(); 
    }, executor);

这允许主线程中的代码继续执行,但是我期望主线程在完成后会死掉,并且将来会继续在其自己的线程中工作,但是即使主线程处于未完成状态,主线程也将保持活动状态直到CompletableFuture完成不再做任何事情。

我对此很陌生,我错过了什么吗? 可能吗

任何帮助将不胜感激!!!

实际上,如果您的主线程不等待CompletableFuture.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);
}

但是Java虚拟机将继续执行线程,直到发生以下任何一种情况

  • 已调用类Runtime的退出方法,并且安全管理器已允许进行退出操作。
  • 不是守护程序线程的所有线程都已死,要么通过从调用返回到run方法,要么抛出传播到run方法之外的异常。

这意味着即使主线程已死,虚拟机仍可以继续工作,因为Executors.newFixedThreadPool(10)创建的所有线程都是非守护进程 您可以在Executors类的defaultThreadFactory()方法的文档中阅读有关它的信息

每个新线程都被创建为非守护线程,其优先级设置为Thread.NORM_PRIORITY中的较小者,并且该线程组中允许的最大优先级

主线程会等待,直到所有其他非守护进程线程都已完成,然后再清理并退出该进程:

http://hg.openjdk.java.net/jdk7/jdk7/hotspot/file/9b0ca45cd756/src/share/vm/runtime/thread.cpp#l3629

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM