读书人

CountDownLatch关于赛事的例子

发布时间: 2012-10-12 10:17:04 作者: rapoo

CountDownLatch关于比赛的例子

package com.test;import java.util.Random;import java.util.concurrent.CountDownLatch;import java.util.concurrent.ExecutorService;import java.util.concurrent.Executors;public class CountDownLatchTest{/** * @param args */public static void main(String[] args){final CountDownLatch referee = new CountDownLatch(1); // 1名裁判final CountDownLatch athlete = new CountDownLatch(3); // 3个运行员ExecutorService pool = Executors.newCachedThreadPool();for (int i = 0; i < 3; i++){pool.execute(new Runnable(){public void run(){System.out.println("运动员:"+ Thread.currentThread().getName() + "准备就绪!");try{referee.await();System.out.println("运动员:"+ Thread.currentThread().getName() + "开始起跑!");Thread.sleep(new Random().nextInt(10000));}catch (InterruptedException e){e.printStackTrace();}athlete.countDown();System.out.println("运行员:"+ Thread.currentThread().getName() + "完成比赛!");}});}try{Thread.sleep(new Random().nextInt(10000));System.out.println("裁判:"+ Thread.currentThread().getName() + "命令发出");referee.countDown();   //起跑命令System.out.println("裁判:"+ Thread.currentThread().getName() + "等待结果");athlete.await();System.out.println("裁判:"+ Thread.currentThread().getName() + "公布结果");}catch (InterruptedException e){e.printStackTrace();}pool.shutdown();}}

读书人网 >编程

热点推荐