中文字幕在线观看,亚洲а∨天堂久久精品9966,亚洲成a人片在线观看你懂的,亚洲av成人片无码网站,亚洲国产精品无码久久久五月天

Java中CountDownLatch用法

2018-07-20    來源:open-open

容器云強(qiáng)勢上線!快速搭建集群,上萬Linux鏡像隨意使用

CountDownLatch類是一個同步計(jì)數(shù)器,構(gòu)造時傳入int參數(shù),該參數(shù)就是計(jì)數(shù)器的初始值,每調(diào)用一次countDown()方法,計(jì)數(shù)器減1,計(jì)數(shù)器大于0 時,await()方法會阻塞程序繼續(xù)執(zhí)行

CountDownLatch如其所寫,是一個倒計(jì)數(shù)的鎖存器,當(dāng)計(jì)數(shù)減至0時觸發(fā)特定的事件。利用這種特性,可以讓主線程等待子線程的結(jié)束。下面以一個模擬運(yùn)動員比賽的例子加以說明。

import java.util.concurrent.CountDownLatch;
  import java.util.concurrent.Executor;
  import java.util.concurrent.ExecutorService;
  import java.util.concurrent.Executors;

  public class CountDownLatchDemo {
     private static final int PLAYER_AMOUNT = 5;
     public CountDownLatchDemo() {
         // TODO Auto-generated constructor stub    
      }
     /**
      * @param args
      */
     public static void main(String[] args) {
         // TODO Auto-generated method stub
         //對于每位運(yùn)動員,CountDownLatch減1后即結(jié)束比賽
         CountDownLatch begin = new CountDownLatch(1);
         //對于整個比賽,所有運(yùn)動員結(jié)束后才算結(jié)束
         CountDownLatch end = new CountDownLatch(PLAYER_AMOUNT);
         Player[] plays = new Player[PLAYER_AMOUNT];

         for(int i=0;i<PLAYER_AMOUNT;i++)
             plays[i] = new Player(i+1,begin,end);

         //設(shè)置特定的線程池,大小為5
         ExecutorService exe = Executors.newFixedThreadPool(PLAYER_AMOUNT);
         for(Player p:plays)
             exe.execute(p);            //分配線程
         System.out.println("Race begins!");
         begin.countDown();
         try{
             end.await();            //等待end狀態(tài)變?yōu)?,即為比賽結(jié)束
         }catch (InterruptedException e) {
             // TODO: handle exception
             e.printStackTrace();
         }finally{
             System.out.println("Race ends!");
         }
         exe.shutdown();
     }
 }

接下來是Player類

```java import java.util.concurrent.CountDownLatch;

public class Player implements Runnable {

 private int id;
 private CountDownLatch begin;
 private CountDownLatch end;
 public Player(int i, CountDownLatch begin, CountDownLatch end) {
     // TODO Auto-generated constructor stub
     super();
     this.id = i;
     this.begin = begin;
     this.end = end;
 }

 @Override
 public void run() {
     // TODO Auto-generated method stub
     try{
         begin.await();        //等待begin的狀態(tài)為0
         Thread.sleep((long)(Math.random()*100));    //隨機(jī)分配時間,即運(yùn)動員完成時間
         System.out.println("Play"+id+" arrived.");
     }catch (InterruptedException e) {
         // TODO: handle exception
         e.printStackTrace();
     }finally{
         end.countDown();    //使end狀態(tài)減1,最終減至0
     }
 }

} ```

標(biāo)簽:

版權(quán)申明:本站文章部分自網(wǎng)絡(luò),如有侵權(quán),請聯(lián)系:west999com@outlook.com
特別注意:本站所有轉(zhuǎn)載文章言論不代表本站觀點(diǎn)!
本站所提供的圖片等素材,版權(quán)歸原作者所有,如需使用,請與原作者聯(lián)系。

上一篇:php調(diào)用mysql存儲過程返回結(jié)果集

下一篇:java調(diào)整圖片的亮度