Java - CountDownLatch與CyclicBarrier的區別

類型 定義 例子 超時例子
CountDownLatch 一個(或多個)線程等待其他線程(彼此獨立)執行完成 每個人(其他線程)下班打卡(countDown)後,各回各家(彼此獨立);等人都走光後,保衛大爺(等待線程)才關門(await) 保衛大爺(等待線程)到點就關門(await),即使還有人沒下班
CyclicBarrier 多個線程互相等待,直到所有線程到達同一個同步點。並且可以重複使用(節能環保 開會時,一般需要參會人(多個線程)都到會議室(await同步點)後,才能開會 參會人(多個線程)等待(await)一定時間後,即使有人缺席,還是要開會

CountDownLatch示例

代碼

     public static void main(String[] args) throws InterruptedException {
        CountDownLatch countDownLatch = new CountDownLatch(3);
        ExecutorService threadPool = Executors.newFixedThreadPool(10);
        int threadCount = 3;
        for (int i = 0; i < threadCount; i++) {
            final int threadNum = i;
            Thread.sleep(1000);
            threadPool.execute(() -> {
                try {
                    System.out.printf("開始上班::threadNum=%d time=%s %n", threadNum, getTime());
                    // 上班8毫秒(黑人問號???)
                    Thread.sleep(8);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.printf("打卡下班::threadNum=%d time=%s %n", threadNum, getTime());
                countDownLatch.countDown();
                System.out.printf("打卡完畢,各回各家::threadNum=%d time=%s %n", threadNum, getTime());
                System.out.println("**********\n");
            });
        }

        System.out.println("保衛大爺等待關門...");
        countDownLatch.await();
        threadPool.shutdown();
        System.out.println("保衛大爺關門回家!");
    }

    private static String getTime() {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("HH:mm:ss S");
        return simpleDateFormat.format(new Date());
    }

結果

在這裏插入圖片描述

CyclicBarrier示例

代碼

    public static void main(String[] args) throws InterruptedException {
        CyclicBarrier cyclicBarrier = new CyclicBarrier(3);
        ExecutorService threadPool = Executors.newFixedThreadPool(10);
        int threadCount = 3;
        for (int i = 0; i < threadCount; i++) {
            final int threadNum = i;
            Thread.sleep(1000);
            threadPool.execute(() -> {
                try {
                    System.out.printf("到達會議室::threadNum=%d time=%s %n", threadNum, getTime());
                    System.out.printf("已等待人數::%d 人%n", cyclicBarrier.getNumberWaiting());
                    System.out.println("**********\n");
                    cyclicBarrier.await();
                    System.out.printf("開始開會::threadNum=%d time=%s %n", threadNum, getTime());
                } catch (InterruptedException | BrokenBarrierException e) {
                    e.printStackTrace();
                }
            });
        }
        threadPool.shutdown();
    }

    private static String getTime() {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("HH:mm:ss S");
        return simpleDateFormat.format(new Date());
    }

結果

在這裏插入圖片描述

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章