国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁(yè) > 編程 > Java > 正文

Java中CountDownLatch用法解析

2019-11-26 13:15:24
字體:
來(lái)源:轉(zhuǎn)載
供稿:網(wǎng)友

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

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

 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     //對(duì)于每位運(yùn)動(dòng)員,CountDownLatch減1后即結(jié)束比賽     CountDownLatch begin = new CountDownLatch(1);     //對(duì)于整個(gè)比賽,所有運(yùn)動(dòng)員結(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();   } }

接下來(lái)是Player類

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ī)分配時(shí)間,即運(yùn)動(dòng)員完成時(shí)間       System.out.println("Play"+id+" arrived.");     }catch (InterruptedException e) {       // TODO: handle exception       e.printStackTrace();     }finally{       end.countDown();  //使end狀態(tài)減1,最終減至0     }   } }

以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持武林網(wǎng)。

發(fā)表評(píng)論 共有條評(píng)論
用戶名: 密碼:
驗(yàn)證碼: 匿名發(fā)表
主站蜘蛛池模板: 邢台县| 张北县| 石景山区| 米林县| 平谷区| 崇礼县| 溆浦县| 赤壁市| 乐清市| 天水市| 潢川县| 平乐县| 福泉市| 西丰县| 松阳县| 越西县| 宜昌市| 西乌| 宜兴市| 敖汉旗| 宁强县| 孝感市| 内黄县| 固始县| 阿克苏市| 得荣县| 林西县| 清远市| 托克逊县| 汉川市| 武强县| 林州市| 赣州市| 巴里| 大悟县| 包头市| 岳普湖县| 和平县| 綦江县| 涟水县| 蓬安县|