我的代码:
public class MyStudy {
public void start() throws Exception{
CompletableFuture<String> cf = CompletableFuture.supplyAsync(MyStudy::task);
//异步任务完成
cf.thenAccept((result) -> {
System.out.println("successful");
});
//标记主线程结束
System.out.println("main main main thread is ended");
}
static String task(){
while (true){
try {
//标记子线程进行
System.out.println("executing...");
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
问题内容:
CompletableFuture.supplyAsync()提交的异步任务由java.util.concurrent.ForkJoinPool线程池接管,而该线程中的线程默认为守护线程,那么我的问题是:
- 如果主线程结束了,而子线程中的异步任务还没结束会怎么样?
- 如果我想正确、保险的处理回调返回值,必须在thenAccept前通过join方法等待子线程中的异步任务完成吗?(毕竟不知道主线程什么时候会结束,也不知道子线程什么时候会处理完,所以个人认为join是保险的方法)
以下是我个人理解的逻辑图,如有不对,请各位批评