8中使用CompletableFuture启动异步任务并使主线程

8中使用CompletableFuture启动异步任务并使主线程

本文介绍了如何在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);

这允许主线程中的代码继续运行,但是我希望主线程在完成时会死掉,并且将来会继续在其自己的线程中工作,但是即使CompletableFuture完成,主线程仍会保持活动状态主线程不再执行任何操作.

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!!!

推荐答案

实际上,如果您的主线程没有等待CompletableFuture.get()或任何其他阻塞方法,则该线程将尽快死掉到达main方法的末尾.

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

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

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

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:

这篇关于如何在Java 8中使用CompletableFuture启动异步任务并使主线程完成并退出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-11 21:54