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