java 多線程 CountDownLatch用法

來源:互聯網
上載者:User

標籤:

ountDownLatch,一個同步輔助類,在完成一組正在其他線程中執行的操作之前,它允許一個或多個線程一直等待。

主要方法

 public CountDownLatch(int count);

 public void countDown();

 public void await() throws InterruptedException
 

構造方法參數指定了計數的次數

countDown方法,當前線程調用此方法,則計數減一

awaint方法,調用此方法會一直阻塞當前線程,直到計時器的值為0

 

例子

Java代碼  

  1. public class CountDownLatchDemo {  

  2.     final static SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");  

  3.     public static void main(String[] args) throws InterruptedException {  

  4.         CountDownLatch latch=new CountDownLatch(2);//兩個工人的協作  

  5.         Worker worker1=new Worker("zhang san", 5000, latch);  

  6.         Worker worker2=new Worker("li si", 8000, latch);  

  7.         worker1.start();//  

  8.         worker2.start();//  

  9.         latch.await();//等待所有工人完成工作  

  10.         System.out.println("all work done at "+sdf.format(new Date()));  

  11.     }  

  12.       

  13.       

  14.     static class Worker extends Thread{  

  15.         String workerName;   

  16.         int workTime;  

  17.         CountDownLatch latch;  

  18.         public Worker(String workerName ,int workTime ,CountDownLatch latch){  

  19.              this.workerName=workerName;  

  20.              this.workTime=workTime;  

  21.              this.latch=latch;  

  22.         }  

  23.         public void run(){  

  24.             System.out.println("Worker "+workerName+" do work begin at "+sdf.format(new Date()));  

  25.             doWork();//工作了  

  26.             System.out.println("Worker "+workerName+" do work complete at "+sdf.format(new Date()));  

  27.             latch.countDown();//工人完成工作,計數器減一  

  28.   

  29.         }  

  30.           

  31.         private void doWork(){  

  32.             try {  

  33.                 Thread.sleep(workTime);  

  34.             } catch (InterruptedException e) {  

  35.                 e.printStackTrace();  

  36.             }  

  37.         }  

  38.     }  

  39.       

  40.        

  41. }  

 

輸出:

Worker zhang san do work begin at 2011-04-14 11:05:11
Worker li si do work begin at 2011-04-14 11:05:11
Worker zhang san do work complete at 2011-04-14 11:05:16
Worker li si do work complete at 2011-04-14 11:05:19
all work done at 2011-04-14 11:05:19


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.