allOf:等待所有任务完成
anyOf:只要有一个任务完成
public class CompletableFutureDemo05 {
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);
CompletableFuture<Integer> future3 = CompletableFuture.supplyAsync(() -> {
System.out.println("线程3开始了" + Thread.currentThread().getName());
int i = 100 / 5;
System.out.println("线程3结束了" + Thread.currentThread().getName());
return i;
}, executor);
CompletableFuture<Object> anyOf = CompletableFuture.anyOf(future1, future2, future3);
anyOf.get();
System.out.println("主任务执行完成...... " +anyOf.get());
CompletableFuture<Void> allOf = CompletableFuture.allOf(future1, future2, future3);
allOf.get();//需要调用get方法阻塞 等待所有任务执行完成
System.out.println("主任务执行完成...... " +future1.get()+":"+future2.get()+":"+future3.get());
}
}