Java並發程式設計(20)並發鎖之倒數鎖CountDownLatch

來源:互聯網
上載者:User

標籤:喚醒   out   線程   dom   style   print   countdown   cst   ready   

1.1. 倒數鎖CountDownLatch

 

CountDownLatch是另外一種線程同步工具。參與倒數的每個線程在工作完成後都執行countDown()方法,當所有線程都執行完後,會喚醒一個或多個在等待倒數計數為0的線程。

 

 

package com.test.concurrence; import java.util.Date;import java.util.Random;import java.util.concurrent.CountDownLatch;import java.util.concurrent.ExecutorService;import java.util.concurrent.Executors; public class CountDownLatchTest { public static void main(String[] args) { final CountDownLatch  countDownLatch = new CountDownLatch(10);ExecutorService  executorService = Executors.newFixedThreadPool(10);//建立10個倒數線程。for(int i=0;i<10;i++){executorService.submit(new Runnable(){ @Overridepublic void run() {try {Thread.sleep(1000* new Random().nextInt(20));} catch (InterruptedException  e) {e.printStackTrace();}//每個參與倒數的線程都倒數1次,計數減1.countDownLatch.countDown();System.out.println("count:" + countDownLatch.getCount() + " , " + new Date()); } });}//建立3個等待倒數計數為0的線程。for(int i=0;i<3;i++){executorService.submit(new Runnable(){ @Overridepublic void run() {try {countDownLatch.await();} catch (InterruptedException e) {e.printStackTrace();}System.out.println("ready:" + countDownLatch.getCount() + " , " + new Date()); } });}  executorService.shutdown();  } } 

 

運行結果如下:

count:9 , Sat Mar 18 23:11:16 CST 2017

count:7 , Sat Mar 18 23:11:18 CST 2017

count:8 , Sat Mar 18 23:11:18 CST 2017

count:6 , Sat Mar 18 23:11:20 CST 2017

count:5 , Sat Mar 18 23:11:25 CST 2017

count:4 , Sat Mar 18 23:11:25 CST 2017

count:3 , Sat Mar 18 23:11:26 CST 2017

count:2 , Sat Mar 18 23:11:27 CST 2017

count:1 , Sat Mar 18 23:11:33 CST 2017

count:0 , Sat Mar 18 23:11:33 CST 2017

ready:0 , Sat Mar 18 23:11:33 CST 2017

ready:0 , Sat Mar 18 23:11:33 CST 2017

ready:0 , Sat Mar 18 23:11:33 CST 2017

 

Java並發程式設計(20)並發鎖之倒數鎖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.