先说结论:
先说结论:
以 thenRun 和 thenRunAsync 为例, 功能都是等待线程执行.
区别主要在线程池的使用上:
1.thenRun(Runnable action): 沿用上一个任务的线程池
2.thenRunAsync(Runnable action): 使用公用的 ForkJoinPool 线程池(不推荐使用公用线程池)
3.thenRunAsync(Runnable action,Executor executor): 使用自定义线程池(推荐)
实际开发推荐写法:使用自定义线程池
测试代码:
public class Test {
/**
* 有后缀 -Async 究竟有什么区别?
* 以 thenRun 和 thenRunAsync 为例, 功能都是等待线程执行.
* 区别主要在线程池的使用上:
* thenRun(Runnable action): 沿用上一个任务的线程池
* thenRunAsync(Runnable action): 使用公用的 ForkJoinPool 线程池(不推荐使用公用线程池)
* thenRunAsync(Runnable action,Executor executor): 使用自定义线程池(推荐)
*/
public static void main(String[] args) throws InterruptedException {
ExecutorService executorService = Executors.newFixedThreadPool(1);
// 使用自定义线程池(推荐)
CompletableFuture<Void> a = CompletableFuture.runAsync(() -> {
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName() + ":runAsync: A.");
}, executorService);
// 沿用上一个任务的线程池
thenRun(a);
// 使用公用的 ForkJoinPool 线程池(不推荐使用公用线程池)
thenRunAsync(a);
System.out.println("main thread:" + Thread.currentThread().getName());
// 主线程不能立马关闭, 否则子线程会直接中断
Thread.sleep(1000);
System.exit(0);
}
public static void thenRun(CompletableFuture<Void> a) {
CompletableFuture<Void> b = a.thenRun(
() -> System.out.println(Thread.currentThread().getName() + ":thenRun:B.")
);
}
public static void thenRunAsync(CompletableFuture<Void> a) {
CompletableFuture<Void> b = a.thenRunAsync(
() -> System.out.println(Thread.currentThread().getName() + ":thenRunAsync:B.")
);
}
}
测试结果:
main thread:main
pool-1-thread-1:runAsync: A.
pool-1-thread-1:thenRun:B.
ForkJoinPool.commonPool-worker-9:thenRunAsync:B.
这三个方法,大家可以分别查看源码,就可以发现里面用的线程创建格式不一样。
关于CompletableFuture的基本用法,可以参考: