Java並發編程之柵欄(CyclicBarrier)詳解

來源:互聯網
上載者:User

標籤:鎖   並發   java並發編程   

  • 柵欄類似閉鎖,但是它們是有區別的.
    閉鎖用來等待事件,而柵欄用於等待其他線程.什麼意思呢?就是說閉鎖用來等待的事件就是countDown事件,只有該countDown事件執行後所有之前在等待的線程才有可能繼續執行;而柵欄沒有類似countDown事件控制線程的執行,只有線程的await方法能控制等待的線程執行.

  • CyclicBarrier強調的是n個線程,大家相互等待,只要有一個沒完成,所有人都得等著。

情境分析:10個人去春遊,規定達到一個地點後才能繼續前行.代碼如下

import java.util.concurrent.BrokenBarrierException;import java.util.concurrent.CyclicBarrier;class CyclicBarrierWorker implements Runnable {    private int id;    private CyclicBarrier barrier;    public CyclicBarrierWorker(int id, final CyclicBarrier barrier) {        this.id = id;        this.barrier = barrier;    }    @Override    public void run() {        // TODO Auto-generated method stub        try {            System.out.println(id + " th people wait");            barrier.await(); // 大家等待最後一個線程到達        } catch (InterruptedException | BrokenBarrierException e) {            // TODO Auto-generated catch block            e.printStackTrace();        }    }}public class TestCyclicBarrier {    public static void main(String[] args) {        int num = 10;        CyclicBarrier barrier = new CyclicBarrier(num, new Runnable() {            @Override            public void run() {                // TODO Auto-generated method stub                System.out.println("go on together!");            }        });        for (int i = 1; i <= num; i++) {            new Thread(new CyclicBarrierWorker(i, barrier)).start();        }    }}

輸出

1 th people wait2 th people wait3 th people wait4 th people wait5 th people wait7 th people wait8 th people wait6 th people wait9 th people wait10 th people waitgo on together!

Java並發編程之柵欄(CyclicBarrier)詳解

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.