java8中新引入了批量线程处理类CompletableFuture
 CompletableFuture.allOf是与的关系, 每个都要执行完
 CompletableFuture.anyOf是或的关系, 其中一个执行完
 以下示例代码:
CompletableFuture.allOf(CompletableFuture.runAsync(() -> {Thread.currentThread().setName("线程A");for (int i = 0; i < 10; i++) {try {System.out.println(Thread.currentThread().getName()+"-"+i);TimeUnit.MILLISECONDS.sleep(new Random().nextInt(2000));} catch (InterruptedException e) {throw new RuntimeException(e);}}
}).thenAccept(unused -> {//线程A执行结束执行System.out.println(Thread.currentThread().getName()+"结束");
}),CompletableFuture.runAsync(() -> {Thread.currentThread().setName("线程B");for (int i = 0; i < 10; i++) {try {System.out.println(Thread.currentThread().getName()+"-"+i);TimeUnit.MILLISECONDS.sleep(new Random().nextInt(1000));} catch (InterruptedException e) {throw new RuntimeException(e);}}
}).thenAccept(unused -> {//线程B执行结束执行System.out.println(Thread.currentThread().getName()+"结束");
})).get();
System.out.println("End");
} catch (InterruptedException | ExecutionException e) {
throw new RuntimeException(e);
}
执行结果:
 线程A-0
 线程B-0
 线程B-1
 线程B-2
 线程B-3
 线程A-1
 线程B-4
 线程B-5
 线程A-2
 线程B-6
 线程B-7
 线程B-8
 线程B-9
 线程A-3
 线程B结束
 线程A-4
 线程A-5
 线程A-6
 线程A-7
 线程A-8
 线程A-9
 线程A结束
 End