線程阻塞(一),CountDownLatch屋彪、CyclicBarrier介紹

遇到一個(gè)筆試題:5個(gè)線程內(nèi)部打印hello和word所宰,hello在前,要求提供一種方法使得5個(gè)線程先全部打印出hello后再打印5個(gè)word

首先想到的是CountDownLatch畜挥、CyclicBarrier這類線程阻塞工具仔粥,趁此機(jī)會(huì),總結(jié)下這幾個(gè)工具的用法吧蟹但。

1躯泰、CountDownLatch

先看下源碼吧,這是構(gòu)造方法

/**
     * Constructs a {@code CountDownLatch} initialized with the given count.
     *
     * @param count the number of times {@link #countDown} must be invoked
     *        before threads can pass through {@link #await}
     * @throws IllegalArgumentException if {@code count} is negative
     */
    public CountDownLatch(int count) {//count為計(jì)數(shù)值  
        if (count < 0) throw new IllegalArgumentException("count < 0");
        this.sync = new Sync(count);
    }

還有幾個(gè)主要的方法

public void await() throws InterruptedException {};   //調(diào)用await()方法后線程會(huì)被掛起华糖,等待直到count值為0才繼續(xù)執(zhí)行麦向,除非線程Intercept
public boolean await(long timeout, TimeUnit unit) throws InterruptedException {};  //和await()類似,只不過等待一定的時(shí)間后count值還沒變?yōu)?的話就會(huì)繼續(xù)執(zhí)行  
public void countDown() {};  //將count值減1  

先寫一個(gè)簡單的例子客叉,比如5個(gè)線程都打印完HelloWorld 后诵竭,打印一條語句

    public static void main(String[] args) {
        CountDownLatch latch = new CountDownLatch(5);
        for (int i = 0; i < 5; i++) {
            new PrintThread(latch, i).start();
        }
        try {
            latch.await();//等待,直到此CountDownLatch里面的count=0
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("******** Print Over ***********");

    }

    static class PrintThread extends Thread {
        CountDownLatch latch;
        int id;

        public PrintThread(CountDownLatch latch, int id) {
            this.latch = latch;
            this.id = id;
        }

        @Override
        public void run() {
            try {
                sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println("Hello World " + id);
            this.latch.countDown();//在做完工作后兼搏,countDown減1
        }
    }

結(jié)果如下

Hello World 0
Hello World 3
Hello World 2
Hello World 1
Hello World 4
******** Print Over ***********

工作線程每次執(zhí)行完后卵慰,countDown()減1,await()掛起向族,先在那等著呵燕,直到count=0的時(shí)候,才繼續(xù)向下執(zhí)行件相。
好了再扭,回到開始的題目氧苍,稍微改下就可以了

    public static void main(String[] args) {
        CountDownLatch latch = new CountDownLatch(5);
        for (int i = 0; i < 5; i++) {
            new PrintThread(latch, i).start();
        }
    }

    static class PrintThread extends Thread {
        CountDownLatch latch;
        int id;

        public PrintThread(CountDownLatch latch, int id) {
            this.latch = latch;
            this.id = id;
        }

        @Override
        public void run() {
            System.out.println("Hello " + id);
            this.latch.countDown();
            try {
                this.latch.await();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println("World " + id);
        }
    }

結(jié)果如下

Hello 0
Hello 3
Hello 4
Hello 2
Hello 1
World 1
World 2
World 3
World 4
World 0

同一個(gè)CountDownLatch對象,在線程中泛范,打印完第一條"Hello"語句后让虐,countDown(),然后await()掛起罢荡,count=0的時(shí)候赡突,再向下打印"World" 語句

2、CyclicBarrier

先看下構(gòu)造方法

  /**
     * Creates a new <tt>CyclicBarrier</tt> that will trip when the
     * given number of parties (threads) are waiting upon it, and
     * does not perform a predefined action when the barrier is tripped.
     *
     * @param parties the number of threads that must invoke {@link #await}
     *        before the barrier is tripped
     * @throws IllegalArgumentException if {@code parties} is less than 1
     */
    public CyclicBarrier(int parties) {
        this(parties, null);
    }
   /**
     * Creates a new <tt>CyclicBarrier</tt> that will trip when the
     * given number of parties (threads) are waiting upon it, and which
     * will execute the given barrier action when the barrier is tripped,
     * performed by the last thread entering the barrier.
     *
     * @param parties the number of threads that must invoke {@link #await}
     *        before the barrier is tripped
     * @param barrierAction the command to execute when the barrier is
     *        tripped, or {@code null} if there is no action
     * @throws IllegalArgumentException if {@code parties} is less than 1
     */
    public CyclicBarrier(int parties, Runnable barrierAction) {
        if (parties <= 0) throw new IllegalArgumentException();
        this.parties = parties;
        this.count = parties;
        this.barrierCommand = barrierAction;
    }

主要方法是

public int await() throws InterruptedException, BrokenBarrierException {};//掛起當(dāng)前線程区赵,直至所有線程都到達(dá)阻塞狀態(tài)(即所有線程都執(zhí)行到了await方法)再執(zhí)行await后面的任務(wù)惭缰;  
public int await(long timeout, TimeUnit unit)throws InterruptedException,BrokenBarrierException,TimeoutException {};//讓這些線程等待至一定的時(shí)間,如果還有線程沒有到達(dá)阻塞狀態(tài)就直接讓已經(jīng)到達(dá)阻塞狀態(tài)的線程執(zhí)行后續(xù)任務(wù)  

回到最開始的題目

public static void main(String[] args) {
        CyclicBarrier cyclicBarrier = new CyclicBarrier(5);
        for (int i = 0; i < 5; i++) {
            new PrintThread(cyclicBarrier, i ).start();
        }
        System.out.println("******** Print Main ***********");
    }

    static class PrintThread extends Thread {
        CyclicBarrier cyclicBarrier;
        int id;

        public PrintThread(CyclicBarrier cyclicBarrier, int id) {
            this.cyclicBarrier = cyclicBarrier;
            this.id = id;
        }

        @Override
        public void run() {
            System.out.println("Hello " + id);
            try {
                this.cyclicBarrier.await();
            } catch (InterruptedException | BrokenBarrierException e) {
                e.printStackTrace();
            }
            System.out.println("World " + id);
        }
    }

執(zhí)行結(jié)果如下

Hello 0
******** Print Main ***********
Hello 3
Hello 2
Hello 1
Hello 4
World 0
World 2
World 3
World 4
World 1

在執(zhí)行完打印"Hello"任務(wù)后笼才,調(diào)用CyclicBarrier的await()方法漱受,線程阻塞在這里,等所有線程都await()了骡送,再執(zhí)行以下的任務(wù)昂羡,打印"World"。
另外摔踱,CyclicBarrier第二個(gè)構(gòu)造方法里有一個(gè)Runnable類型的參數(shù)虐先,看下注釋,

// 等阻塞釋放了派敷,再執(zhí)行的指令
@param barrierAction the command to execute when the barrier is tripped 

我們用另外一個(gè)構(gòu)造方法試試

CyclicBarrier cyclicBarrier = new CyclicBarrier(5, new Runnable() {

            @Override
            public void run() {
                System.out.println("******** Print Main ***********");
            }
        });

執(zhí)行結(jié)果如下

Hello 0
Hello 2
Hello 1
Hello 4
Hello 3
******** Print Main ***********
World 3
World 0
World 1
World 2
World 4

所有的"Hello" 打印完蛹批,再執(zhí)行這個(gè)barrierAction參數(shù),而且膀息,需要注意的是般眉,等barrierAction執(zhí)行完畢后,才會(huì)再往下執(zhí)行潜支。

總結(jié)

CountDownLatch甸赃、CyclicBarrier都能實(shí)現(xiàn)線程阻塞,區(qū)別是在使用過程中CountDownLatch調(diào)用await()方法僅實(shí)現(xiàn)阻塞冗酿,對計(jì)數(shù)沒有影響埠对,線程執(zhí)行完需要手動(dòng)countDown()更新計(jì)數(shù),而CyclicBarrier調(diào)用await()方法后裁替,會(huì)統(tǒng)計(jì)是否全部await()了项玛,如果沒有全部await(),就阻塞弱判,也就是說襟沮,CyclicBarrier的await()方法也參與計(jì)數(shù)了;另外一方面,CountDownLatch不能復(fù)用开伏,CyclicBarrier可以在某個(gè)線程中調(diào)用它的reset()方法復(fù)用膀跌。

補(bǔ)充

CountDownLatch、CyclicBarrier和后面要講的Semaphore固灵、JDK 1.6版本的FutureTask都是基于AbstractQueuedSynchronizer機(jī)制實(shí)現(xiàn)同步的捅伤,源碼解析可參考:http://brokendreams.iteye.com/blog/2250372

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個(gè)濱河市巫玻,隨后出現(xiàn)的幾起案子丛忆,更是在濱河造成了極大的恐慌,老刑警劉巖仍秤,帶你破解...
    沈念sama閱讀 216,470評論 6 501
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件熄诡,死亡現(xiàn)場離奇詭異,居然都是意外死亡诗力,警方通過查閱死者的電腦和手機(jī)粮彤,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 92,393評論 3 392
  • 文/潘曉璐 我一進(jìn)店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來姜骡,“玉大人,你說我怎么就攤上這事屿良∪Τ海” “怎么了?”我有些...
    開封第一講書人閱讀 162,577評論 0 353
  • 文/不壞的土叔 我叫張陵尘惧,是天一觀的道長康栈。 經(jīng)常有香客問我,道長喷橙,這世上最難降的妖魔是什么啥么? 我笑而不...
    開封第一講書人閱讀 58,176評論 1 292
  • 正文 為了忘掉前任,我火速辦了婚禮贰逾,結(jié)果婚禮上悬荣,老公的妹妹穿的比我還像新娘疙剑。我一直安慰自己氯迂,他們只是感情好,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,189評論 6 388
  • 文/花漫 我一把揭開白布言缤。 她就那樣靜靜地躺著嚼蚀,像睡著了一般。 火紅的嫁衣襯著肌膚如雪管挟。 梳的紋絲不亂的頭發(fā)上轿曙,一...
    開封第一講書人閱讀 51,155評論 1 299
  • 那天,我揣著相機(jī)與錄音,去河邊找鬼导帝。 笑死守谓,一個(gè)胖子當(dāng)著我的面吹牛,可吹牛的內(nèi)容都是我干的舟扎。 我是一名探鬼主播分飞,決...
    沈念sama閱讀 40,041評論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼睹限!你這毒婦竟也來了譬猫?” 一聲冷哼從身側(cè)響起,我...
    開封第一講書人閱讀 38,903評論 0 274
  • 序言:老撾萬榮一對情侶失蹤羡疗,失蹤者是張志新(化名)和其女友劉穎染服,沒想到半個(gè)月后,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體叨恨,經(jīng)...
    沈念sama閱讀 45,319評論 1 310
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡柳刮,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 37,539評論 2 332
  • 正文 我和宋清朗相戀三年,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了痒钝。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片秉颗。...
    茶點(diǎn)故事閱讀 39,703評論 1 348
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡,死狀恐怖送矩,靈堂內(nèi)的尸體忽然破棺而出蚕甥,到底是詐尸還是另有隱情,我是刑警寧澤栋荸,帶...
    沈念sama閱讀 35,417評論 5 343
  • 正文 年R本政府宣布菇怀,位于F島的核電站,受9級特大地震影響晌块,放射性物質(zhì)發(fā)生泄漏爱沟。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,013評論 3 325
  • 文/蒙蒙 一匆背、第九天 我趴在偏房一處隱蔽的房頂上張望呼伸。 院中可真熱鬧,春花似錦钝尸、人聲如沸蜂大。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,664評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽奶浦。三九已至,卻和暖如春踢星,著一層夾襖步出監(jiān)牢的瞬間澳叉,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 32,818評論 1 269
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留成洗,地道東北人五督。 一個(gè)月前我還...
    沈念sama閱讀 47,711評論 2 368
  • 正文 我出身青樓,卻偏偏與公主長得像瓶殃,于是被迫代替她去往敵國和親充包。 傳聞我的和親對象是個(gè)殘疾皇子,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 44,601評論 2 353

推薦閱讀更多精彩內(nèi)容