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

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

首先想到的是CountDownLatch、CyclicBarrier這類(lèi)線程阻塞工具,趁此機(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()類(lèi)似,只不過(guò)等待一定的時(shí)間后count值還沒(méi)變?yōu)?的話(huà)就會(huì)繼續(xù)執(zhí)行  
public void countDown() {};  //將count值減1  

先寫(xiě)一個(gè)簡(jiǎn)單的例子,比如5個(gè)線程都打印完HelloWorld 后,打印一條語(yǔ)句

    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í)行。
好了,回到開(kāi)始的題目,稍微改下就可以了

    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對(duì)象,在線程中,打印完第一條"Hello"語(yǔ)句后,countDown(),然后await()掛起,count=0的時(shí)候,再向下打印"World" 語(yǔ)句

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í)間,如果還有線程沒(méi)有到達(dá)阻塞狀態(tài)就直接讓已經(jīng)到達(dá)阻塞狀態(tài)的線程執(zhí)行后續(xù)任務(wù)  

回到最開(kāi)始的題目

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類(lèi)型的參數(shù),看下注釋?zhuān)?/p>

// 等阻塞釋放了,再執(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ū)別是在使用過(guò)程中CountDownLatch調(diào)用await()方法僅實(shí)現(xiàn)阻塞,對(duì)計(jì)數(shù)沒(méi)有影響,線程執(zhí)行完需要手動(dòng)countDown()更新計(jì)數(shù),而CyclicBarrier調(diào)用await()方法后,會(huì)統(tǒng)計(jì)是否全部await()了,如果沒(méi)有全部await(),就阻塞,也就是說(shuō),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)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容