countDownLatch與cyclicBarrier的區別

在這裏插入圖片描述
countDownLatch舉例說明


public class countDownlatchTest {
    public static void main(String[] args) throws InterruptedException {
        CountDownLatch countDownLatch = new CountDownLatch(5);
        for(int i=0;i<5;i++){
            new Thread(new readNum(i,countDownLatch)).start();
        }
        countDownLatch.await();
        System.out.println("線程執行結束。。。。");
    }
 
    static class readNum  implements Runnable{
        private int id;
        private CountDownLatch latch;
        public readNum(int id,CountDownLatch latch){
            this.id = id;
            this.latch = latch;
        }
        @Override
        public void run() {
            synchronized (this){
                System.out.println("id:"+id);
                latch.countDown();
                System.out.println("線程組任務"+id+"結束,其他任務繼續");
            }
        }
    }
}

運行結果如下

id:0
id:1
線程組任務1結束,其他任務繼續
線程組任務0結束,其他任務繼續
id:2
線程組任務2結束,其他任務繼續
id:4
線程組任務4結束,其他任務繼續
id:3
線程組任務3結束,其他任務繼續
線程執行結束。。。。

cyclicBarrier舉例如下

package com.hanshow.testThread;
 
import java.util.concurrent.CyclicBarrier;
 
/**
 * PROJECT_NAME:downLoad
 * Author:lucaifang
 * Date:2016/3/18
 */
public class cyclicBarrierTest {
    public static void main(String[] args) throws InterruptedException {
        CyclicBarrier cyclicBarrier = new CyclicBarrier(5, new Runnable() {
            @Override
            public void run() {
                System.out.println("線程組執行結束");
            }
        });
        for (int i = 0; i < 5; i++) {
            new Thread(new readNum(i,cyclicBarrier)).start();
        }
        Thread.sleep(5000);
        //CyclicBarrier 可以重複利用,
        // 這個是CountDownLatch做不到的
        for (int i = 11; i < 16; i++) {
            new Thread(new readNum(i,cyclicBarrier)).start();
        }
    }
    static class readNum  implements Runnable{
        private int id;
        private CyclicBarrier cyc;
        public readNum(int id,CyclicBarrier cyc){
            this.id = id;
            this.cyc = cyc;
        }
        @Override
        public void run() {
        	
        	 System.out.println("id:"+id);
             try {
                 cyc.await();
                 System.out.println("線程組任務" + id + "結束,其他任務繼續");
             } catch (Exception e) {
                 e.printStackTrace();
             }
        	
            /*synchronized (this){
                System.out.println("id:"+id);
                try {
                    cyc.await();
                    System.out.println("線程組任務" + id + "結束,其他任務繼續");
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }*/
        }
    }
}


id:0
id:2
id:3
id:1
id:4
線程組執行結束
線程組任務4結束,其他任務繼續
線程組任務2結束,其他任務繼續
線程組任務1結束,其他任務繼續
線程組任務3結束,其他任務繼續
線程組任務0結束,其他任務繼續
id:11
id:12
id:13
id:14
id:15
線程組執行結束
線程組任務15結束,其他任務繼續
線程組任務11結束,其他任務繼續
線程組任務12結束,其他任務繼續
線程組任務14結束,其他任務繼續
線程組任務13結束,其他任務繼續

擴展
在這裏插入圖片描述

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