java 多线程 CountDownLatch&CyclicBarrier

多线程笔记

  • CountDownLatch

用于一个线程或多个线程等待多个线程

 class CountdownLatchExample {

    public static void main(String[] args) throws InterruptedException {
        final int totalThread = 10;
        CountDownLatch countDownLatch = new CountDownLatch(totalThread);
        ExecutorService executorService = Executors.newCachedThreadPool();
        for (int i = 0; i < totalThread; i++) {
            executorService.execute(() -> {
                System.out.print("run.." + Thread.currentThread().getId() + "\n");
                countDownLatch.countDown();
            });
        }
        countDownLatch.await();
        System.out.println("end");
        executorService.shutdown();
    }
}
  • CyclicBarrier

用于多个线程互相等待,达到一致状态后,这些线程才继续执行

class CyclicBarrierExample {

    public static void main(String[] args) {
        final int totalThread = 10;
        CyclicBarrier cyclicBarrier = new CyclicBarrier(totalThread);
        ExecutorService executorService = Executors.newCachedThreadPool();
        for (int i = 0; i < totalThread; i++) {
            executorService.execute(() -> {
                System.out.print("before..");
                try {
                    cyclicBarrier.await();
                } catch (InterruptedException | BrokenBarrierException e) {
                    e.printStackTrace();
                }
                System.out.print("after..");
            });
        }
        executorService.shutdown();
    }
}
  • 线程状态
状态
新建 NEW
可运行 RUNABLE
阻塞 BLOCKED
无限期等待 WAITING
限期等待 TIME_WAITING
死亡 TERMINATED
posted @ 2022-06-16 11:04  GHzz  阅读(24)  评论(0编辑  收藏  举报