线程1:
CompletableFuture<String> future01 = CompletableFuture.supplyAsync(() -> {
System.out.println("任务1线程:" + Thread.currentThread().getId());
int i = 6 / 2;//仅测试计算
System.out.println("任务1结束:");
return i;
}, executor);
CompletableFuture<String> future02 = CompletableFuture.supplyAsync(() -> {
System.out.println("任务2线程:" + Thread.currentThread().getId());
System.out.println("任务2结束:");
return "Hello";
}, executor);
//比较满意的组合多线程
future01.thenAcceptBothAsync(future02, (f1, f2) -> {
System.out.printIn("任务3开始…..之前的结果:”+f1" + "--->" + f2);
}, executor);
//最佳进阶组合,推荐使用
CompletableFuture<String> future = future01.thenCombineAsync(future02, (f1, f2) -> {
return f1 + ":" + f2 + " -> Haha"; //可以得到线程1和 线程2的运行结果并可以自定义组装后的结果在最后在自定义一个线程中返回
}, executor);
System.out.println("main....end...." + future.get());
- 1.
- 2.
- 3.
- 4.
- 5.
- 6.
- 7.
- 8.
- 9.
- 10.
- 11.
- 12.
- 13.
- 14.
- 15.
- 16.
- 17.
- 18.
- 19.
- 20.
- 21.
- 22.
- 23.
- 24.
- 25.
- 26.
- 27.
- 28.
- 29.
- 30.
- 31.