private static CyclicBarrier barrier = new CyclicBarrier(2,() ->{
System.err.println("屏障完成!");
});
public static void main(String[] args) {
ExecutorService executorService = Executors.newFixedThreadPool(2);
executorService.submit(() -> {
try {
System.err.println("A " +Thread.currentThread().getName() +" 执行 1");
barrier.await();//屏障
System.err.println("A " +Thread.currentThread().getName() +" 执行 2");
barrier.await();//屏障
System.err.println("A " +Thread.currentThread().getName() +" 执行 done");
} catch (Exception e) {
e.printStackTrace();
}
});
executorService.submit(() -> {
try {
System.err.println("B " +Thread.currentThread().getName() +" 执行 1");
barrier.await();//屏障
System.err.println("B " +Thread.currentThread().getName() +" 执行 2");
barrier.await();//屏障
System.err.println("B " +Thread.currentThread().getName() +" 执行 done");
} catch (Exception e) {
e.printStackTrace();
}
});
executorService.shutdown();
}