runAfterEither:不能获取完成的线程的返回结果,自身也没有返回结果
* acceptEither:可以获取线程的返回结果,自身没有返回结果
* applyToEither:既可以获取线程的返回结果,自身也有返回结果
public class CompletableFutureDemo04 {
private static ThreadPoolExecutor executor=new ThreadPoolExecutor(5,
50,
10,
TimeUnit.SECONDS,
new LinkedBlockingQueue<>(),
Executors.defaultThreadFactory(),
new ThreadPoolExecutor.AbortPolicy());
//运行时发现 线程会阻塞 等待新的任务去调度
/**
*
* @throws ExecutionException
* @throws InterruptedException
*/
public static void main(String[] args) throws Exception {
CompletableFuture<Integer> future1 = CompletableFuture.supplyAsync(() -> {
System.out.println("线程1开始了" + Thread.currentThread().getName());
int i = 100 / 10;
System.out.println("线程1结束了" + Thread.currentThread().getName());
return i;
}, executor);
CompletableFuture<Integer> future2 = CompletableFuture.supplyAsync(() -> {
System.out.println("线程2开始了" + Thread.currentThread().getName());
int i = 100 / 5;
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("线程2结束了" + Thread.currentThread().getName());
return i;
}, executor);
//runAfterEitherAsync 是不能获取前面线程的返回结果 自身也没有返回结果
future1.runAfterEitherAsync(future2, () -> {
System.out.println("任务3执行了");
},executor);
//acceptEitherAsync 自身没有返回结果 接收上面两个线程其中一个 结果就能正常运行 并且线程1和线程2的返回泛型类型必须相同 可以写成Object
future1.acceptEitherAsync(future2, res -> {
System.out.println("res = " + res);
}, executor);
CompletableFuture<String> stringCompletableFuture = future1.applyToEitherAsync(future2, res -> {
System.out.println("res = " + res);
return res + "--->ok";
}, executor);
System.out.println("stringCompletableFuture:"+stringCompletableFuture.get());
}
}