java並發流程式控制制(CountDownLatch-CycliBarrier)__java

來源:互聯網
上載者:User
1)CountDownLatch 門插銷計數器       1.  啟動線程,然後等待線程結束。即常用的主線程等所有子線程結束後再執行的問題。
public static void main(String[] args)throws Exception { // TODO Auto-generated method stub final int count=10; final CountDownLatch completeLatch = new CountDownLatch(count);//定義了門插銷的數目是10 for(int i=0;i<count;i++){ Thread thread = new Thread("worker thread"+i){ public void run(){ //do xxxx completeLatch.countDown();//減少一根門插銷 } }; thread.start(); } completeLatch.await();//如果門插銷還沒減完則等待。 } 2.啟動很多線程,等待通知才能開始
public static void main(String[] args) throws Exception { // TODO Auto-generated method stub final CountDownLatch startLatch = new CountDownLatch(1);//定義了一根門插銷
for (int i = 0; i < 10; i++) { Thread thread = new Thread("worker thread" + i) { public void run() { try { startLatch.await();//如果門插銷還沒減完則等待 } catch (InterruptedException e) {
} // do xxxx } }; thread.start(); } startLatch.countDown();//減少一根門插銷 }

2) CycliBarrier. 等所有線程都達到一個起跑線後才能開始繼續運行。 public class CycliBarrierTest implements Runnable { private CyclicBarrier barrier;
public CycliBarrierTest(CyclicBarrier barrier) { this.barrier = barrier; }
public void run() { //do xxxx; try { this.barrier.await();//線程運行至此會檢查是否其它線程都到齊了,沒到齊就繼續等待。到齊了就執行barrier的run函數體裡的內容 } catch (Exception e) {
} }
/** * @param args */ public static void main(String[] args) { //參數2代表兩個線程都達到起跑線才開始一起繼續往下執行 CyclicBarrier barrier = new CyclicBarrier(2, new Runnable() { public void run() { //do xxxx; } }); Thread t1 = new Thread(new CycliBarrierTest(barrier)); Thread t2 = new Thread(new CycliBarrierTest(barrier)); t1.start(); t2.start(); }
}         

聯繫我們

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