什么是守护线程
守护线程(Daemon Thread)运行在后台,不会阻止JAVA虚拟机(JVM)的退出,当JVM中所有非守护线程结束运行时,JVM会自动退出。
CompletableFuture
那么CompletableFuture中跑的线程是守护线程还是非守护线程呢。直接来看代码
public static void main(String[] args) throws InterruptedException {
CompletableFuture.runAsync(() ->{
System.out.println("线程名称"+Thread.currentThread());
System.out.println("是否是daemon线程:"+Thread.currentThread().isDaemon());
try {
Thread.sleep(10000);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
System.out.println("CompletableFuture 执行结束==========");
});
System.out.println("主线程执行");
Thread.sleep(3000);
}
主线程执行
线程名称Thread[ForkJoinPool.commonPool-worker-51,5,main]
是否是daemon线程:true
打印结果显示,CompletableFuture默认使用的是ForkJoinPool.commonPool线程池,并且是守护线程。所以这里的线程并没有执行结束,JVM就退出了。
如果你想让CompletableFuture执行完成再退出,可以自定义Executor 线程池
public static CompletableFuture<Void> runAsync(Runnable runnable,
Executor executor)
public static void main(String[] args) throws InterruptedException {
CompletableFuture.runAsync(() ->{
System.out.println("线程名称"+Thread.currentThread());
System.out.println("是否是daemon线程:"+Thread.currentThread().isDaemon());
try {
Thread.sleep(10000);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
System.out.println("CompletableFuture 执行结束==========");
},Executors.newSingleThreadExecutor());
System.out.println("主线程执行");
Thread.sleep(3000);
}
主线程执行
线程名称Thread[pool-1-thread-1,5,main]
是否是daemon线程:false
CompletableFuture 执行结束==========
这样就把CompletableFuture改为了使用非守护线程来执行任务。
注意:这里为了方便直接使用了Executors.newSingleThreadExecutor(),实际使用过程中最好使用ThreadPoolExecutor来自定义一个线程池。
如果使用默认线程池可以使用get()方法来同步等待线程执行完成
public static void main(String[] args) throws InterruptedException, ExecutionException {
CompletableFuture.runAsync(() ->{
System.out.println("线程名称"+Thread.currentThread());
System.out.println("是否是daemon线程:"+Thread.currentThread().isDaemon());
try {
Thread.sleep(10000);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
System.out.println("CompletableFuture 执行结束==========");
}).get();
System.out.println("主线程执行");
Thread.sleep(3000);
}
线程名称Thread[ForkJoinPool.commonPool-worker-51,5,main]
是否是daemon线程:true
CompletableFuture 执行结束==========
主线程执行
这样保留了守护线程,同时主线程会等待CompletableFuture执行完成再执行。
总结
CompletableFuture的默认线程池ForkJoinPool.commonPool()使用的是守护线程,使用的时候要注意。