Java並發之CountDownLatch

來源:互聯網
上載者:User

標籤:ati   until   any   run   latch   java   int   sys   string   

CountDownLatch是Java concurrent包下的一個同步工具。它可以讓一個(或多個)線程等待,直到其他線程中的某些操作完成。

本質上是一個訊號量,我們把它比作一個有N個插銷的大門,它把等待(調用await)的線程擋住了, 直到其他線程把插銷去完了(調用countDown減到0),這批線程才能執行。

下面是根據oracle官方文檔改的一個例子:

/** *  * Sample usage: Here is a pair of classes in which a group of worker threads use two countdown latches: The first is a start signal that prevents any worker from proceeding until the driver is ready for them to proceed; The second is a completion signal that allows the driver to wait until all workers have completed. */public class CountDownLatchDemo {    public static void main(String[] args) throws InterruptedException {        new Driver().run();    }}class Driver {    static final int N = 5;    public void run() throws InterruptedException {        CountDownLatch startSignal = new CountDownLatch(1);        CountDownLatch doneSignal = new CountDownLatch(N);        for (int i=0; i<N; i++) {            new Thread(new Worker(startSignal, doneSignal))                    .start();        }        doSomething(); // don‘t let run yet        startSignal.countDown(); // let all threads proceed        doneSignal.await(); // wait for all to finish        doSomething();    }    private void doSomething() {        System.out.println("doSomething");    }}class Worker implements Runnable {    private CountDownLatch startSignal;    private CountDownLatch doneSignal;    public Worker(CountDownLatch startSignal, CountDownLatch doneSignal) {        this.startSignal = startSignal;        this.doneSignal = doneSignal;    }    public void run() {        try {            startSignal.await();            doWork();            doneSignal.countDown();        } catch (InterruptedException e) {            e.printStackTrace();        }    }    private void doWork() {        System.out.println("worker work.");    }}

把Driver看作是一個監工,Worker看作是工人,有5個。

  • 監工發號施令後,工人們才可以幹活。所以工人幹活前調用startSignal.await(), 直到監工調用startSignal.countDown() 後Worker後續doWork才開始執行。 
  • 工人們幹完活後通知監工,監工才可以接著發號。所以監工調用doneSignal.await()在哪兒等著,直到工人們都幹完活(調用5次doneSignal.countDown())後,才能接著執行。

看下執行結果,有助於理解整個工作過程和latch機制:

doSomething
worker work.
worker work.
worker work.
worker work.
worker work.
doSomething

Java並發之CountDownLatch

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.