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

首頁 > 學(xué)院 > 開發(fā)設(shè)計 > 正文

CountDownLatch使用例子

2019-11-14 22:19:58
字體:
供稿:網(wǎng)友
CountDownLatch使用例子

CountDownLatch是一個同步輔助類,猶如倒計時計數(shù)器,創(chuàng)建對象時通過構(gòu)造方法設(shè)置初始值,調(diào)用CountDownLatch對象的await()方法則處于等待狀態(tài),調(diào)用countDown()方法就將計數(shù)器減1,當(dāng)計數(shù)到達(dá)0時,則所有等待者或單個等待者開始執(zhí)行。

簡單例子

import java.util.concurrent.CountDownLatch;/*** 出發(fā)點:等待所有線程執(zhí)行完成* @author yinchuan.chen**/public class CountDownLatchTest {public static void main(String[] args) throws InterruptedException {CountDownLatch cdl = new CountDownLatch(4);for(int i = 0; i < 4; i++) {final int count = i;Thread t = new Thread(new Runnable() {public void run() {System.out.

注:countDown最好是在finally里面調(diào)用

import java.util.concurrent.CountDownLatch;import java.util.concurrent.ExecutorService;import java.util.concurrent.Executors;public class CountDownLatchDemo {   private static final int PLAYER_AMOUNT = 5;   public CountDownLatchDemo() {    }   /**    * @param args    */   public static void main(String[] args) {       //對于整個比賽,所有運動員結(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,end);              //設(shè)置特定的線程池,大小為5       ExecutorService exe = Executors.newFixedThreadPool(PLAYER_AMOUNT);       for(Player p:plays)           exe.execute(p);            //分配線程       System.out.println("Race begins!");       try{           end.await();            //等待end狀態(tài)變?yōu)?,即為比賽結(jié)束       }catch (InterruptedException e) {           e.printStackTrace();       }finally{           System.out.println("Race ends!");       }       exe.shutdown();   }}class Player implements Runnable {         private int id;    private CountDownLatch end;    public Player(int i, CountDownLatch end) {        super();        this.id = i;        this.end = end;    }    @Override    public void run() {        try{            Thread.sleep((long)(Math.random()*100));    //隨機分配時間,即運動員完成時間            System.out.println("Play"+id+" arrived.");        }catch (InterruptedException e) {            e.printStackTrace();        }finally{            end.countDown();    //使end狀態(tài)減1,最終減至0        }    }}

參考 http://m.survivalescaperooms.com/yezhenhan/archive/2012/01/07/2315652.html

發(fā)表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發(fā)表
主站蜘蛛池模板: 广宗县| 科技| 滦平县| 罗田县| 太仆寺旗| 安龙县| 九龙城区| 宜都市| 南漳县| 清远市| 吉安县| 拉萨市| 神农架林区| 高碑店市| 治多县| 武威市| 临桂县| 那曲县| 克拉玛依市| 西平县| 东乡| 双辽市| 东台市| 宜城市| 白山市| 保山市| 延庆县| 普格县| 大关县| 宁国市| 卢龙县| 平昌县| 古蔺县| 永泰县| 封开县| 清原| 邯郸市| 乡城县| 天全县| 建瓯市| 柘荣县|