码迷,mamicode.com
首页 > 编程语言 > 详细

Java线程池ExecutorService和CountDownLatch的小例子

时间:2015-04-01 17:20:05      阅读:216      评论:0      收藏:0      [点我收藏+]

标签:

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

/**
 * 模拟了100米赛跑,10名选手已经准备就绪,只等裁判一声令下。当所有人都到达终点时,比赛结束。
 * @author liuchao
 *
 */
public class Actor {

    public static void main(String[] args) throws InterruptedException {
        //10名运动员
        final CountDownLatch count = new CountDownLatch(10);
        
        //java的线程池
        final ExecutorService executorService = Executors.newFixedThreadPool(5);
        
        for(int index=1;index<=10;index++){
            final int number = index;
            executorService.submit(new Runnable() {
                public void run() {
                    try {
Thread.sleep((
long) (Math.random()*10000)); System.out.println(number+": arrived"); } catch (InterruptedException e) { e.printStackTrace(); } finally{ //运动员到达终点,count数减一 count.countDown(); } } }); } System.out.println("Game Started"); //等待count数变为0,否则会一直处于等待状态,游戏就没法结束了 count.await(); System.out.println("Game Over"); //关掉线程池 executorService.shutdown(); } }

     运行结果

Game Started
5: arrived
1: arrived
2: arrived
3: arrived
8: arrived
4: arrived
6: arrived
9: arrived
7: arrived
10: arrived
Game Over

Java线程池ExecutorService和CountDownLatch的小例子

标签:

原文地址:http://www.cnblogs.com/liuchao102/p/4383894.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!