CountDownLatch使用

Runner.java 

package com.source.current;
import java.util.Random;
import java.util.concurrent.Callable;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
public class Runner implements Callable<Integer> {
    private CountDownLatch begin;  //裁判
    private CountDownLatch end;    //运动员

    public Runner(CountDownLatch begin, CountDownLatch end) {
        super();
        this.begin = begin;
        this.end = end;
    }
    @Override
    public Integer call() throws Exception {
       int score= new Random().nextInt(10);
       //裁判等待运动员上场
       begin.await();
        TimeUnit.MILLISECONDS.sleep(score);
        // 运动员计数
        end.countDown();
        return score;
    }
}

RunnerImpl.java 

package com.source.current;
import java.util.ArrayList;
import java.util.concurrent.*;
public class RunnerImpl {
    public static void main(String[] args) throws  Exception {
      int   person = 8;
        CountDownLatch  begin=new  CountDownLatch(1); //  裁判
        CountDownLatch end = new CountDownLatch(8);  // 运动员
        ExecutorService executorService = Executors.newFixedThreadPool(person);
        ArrayList<Future<Integer>> list = new ArrayList<Future<Integer>>();

        for (int i = 0; i < person; i++) {
            list.add(executorService.submit(new Runner(begin,end)));
        }

            //枪声响起
            begin.countDown();
            //等待所有运动员跑完
            end.await();
            int  count =0;
           int highScore=0;
            for (Future<Integer> f:list) {
                count+=f.get();
                if(f.get()>highScore){
                    highScore=f.get();
                }
            }
            System.out.println("运动员人数为:"+person+"总分为:"+count+"平均分为:"+count/person+"最高分为:"+highScore);
        executorService.shutdown();
    }
}


运动员人数为:8总分为:38平均分为:4最高分为:9 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值