zoukankan      html  css  js  c++  java
  • Java线程池ExecutorService和CountDownLatch的小例子

    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

  • 相关阅读:
    css设置兼容的透明样式
    mybatis 使用oracle merge into 语句踩坑实录
    eclipse导入SVN上的Maven多模块项目
    jquery.form插件中动态修改表单数据
    java的几种对象(po,dto,dao等)
    redis面试总结
    前段面试准备
    查询各科成绩最好的学生
    Github访问慢解决办法
    该文件有程序在使用
  • 原文地址:https://www.cnblogs.com/liuchao102/p/4383894.html
Copyright © 2011-2022 走看看