CountDownLatch的基本使用
public static void main(String[] args) { CountDownLatch countDownLatch = new CountDownLatch(3); IntStream.range(0, 3).forEach(i -> new Thread(() -> { try { Thread.sleep(2000); System.out.println("hello"); } catch (InterruptedException ex) { ex.printStackTrace(); } finally { countDownLatch.countDown(); } }).start()); System.out.println("启动子线程完毕"); try { countDownLatch.await(); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println("主线程执行完毕");}
CyclicBarrierd的基本使用
public static void main(String[] args) { CyclicBarrier cyclicBarrier = new CyclicBarrier(3, () -> { System.out.println("hello world"); }); for (int i = 0; i < 2; ++i) { for (int n = 0; n < 3; ++n) { new Thread(() -> { try { Thread.sleep((long) (Math.random() * 2000)); int randomInt = new Random().nextInt(500); System.out.println("hello " + randomInt); cyclicBarrier.await(); System.out.println("world " + randomInt); } catch (Exception ex) { ex.printStackTrace(); } }).start(); } } }