CountDownLatch demo

CountDownLatch 同步辅助计时类,主要包含:

一个带计时参数的构造函数:CountDownLatch(int count);

计数减1方法:void countDown();

阻塞当前线程直到所有线程完成即计数器值为0:await() 或 await(long timeout, TimeUnit unit) 使用带参方法时,当计数器值为0或者耗时完时结束

示例:5个员工完成工作耗时,coolPoolSize分配决定了执行时间是否一致

public class CountDownLatchDemo {

    private static final String FORMAT = "yy-MM-dd HH:mm:ss";
    private static final Random RANDOM = new Random();

    public static String getFormat(Date date) {
        SimpleDateFormat sdf = new SimpleDateFormat(FORMAT);
        return sdf.format(date);
    }

    public static void main(String[] args) throws Exception {
        int selfCompleteNum = 1;
        int allCompleteNum = 5;
        CountDownLatch selfDownLatch = new CountDownLatch(selfCompleteNum);
        CountDownLatch countDownLatch = new CountDownLatch(allCompleteNum);
        //添加工人
        Worker[] workers = new Worker[allCompleteNum];
        for (int i = 0; i < allCompleteNum; i++) {
            workers[i] = new Worker("emp" + i, selfDownLatch, countDownLatch);
        }
        //设置线程池,不适用Executors创建是为了规避资源耗尽风险
        ThreadFactory namedThreadFactory = new ThreadFactoryBuilder()
            .setNameFormat("worker-pool-%d").build();
        //coolPoolSize分配
        ExecutorService pool = new ThreadPoolExecutor(5, 20, 0L,
            TimeUnit.MILLISECONDS, new LinkedBlockingDeque<Runnable>(1024),
            namedThreadFactory, new ThreadPoolExecutor.AbortPolicy());
        //分配线程
        for (Worker worker : workers) {
            pool.execute(worker);
        }
        //开始工作
        selfDownLatch.countDown();
        //完成工作
        countDownLatch.await();
        pool.shutdown();
        System.out.println("均完成后的时间:" + getFormat(new Date()));
    }

    private static class Worker extends Thread {
        private String workName;
        private CountDownLatch selfLatch;
        private CountDownLatch latch;

        public Worker(String workName, CountDownLatch selfLatch, CountDownLatch latch) {
            this.workName = workName;
            this.selfLatch = selfLatch;
            this.latch = latch;
        }

        @Override
        public void run() {
            System.out.println("Worker " + workName + " do work begin at " + getFormat(new Date()));
            doWork();
            System.out.println("Worker " + workName + " do work complete at " + getFormat(new Date()));
        }

        private void doWork() {
            try {
                selfLatch.await();
                Thread.sleep(RANDOM.nextInt(3) * 1000 + 1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            } finally {
                latch.countDown();
                System.out.println("Worker " + workName + " CountDownLatch count " + latch.getCount());
            }
        }
    }
}
返回结果如下:

Worker emp1 do work begin at 17-06-15 16:42:51
Worker emp3 do work begin at 17-06-15 16:42:51
Worker emp2 do work begin at 17-06-15 16:42:51
Worker emp4 do work begin at 17-06-15 16:42:51
Worker emp0 do work begin at 17-06-15 16:42:51
Worker emp0 CountDownLatch count 4
Worker emp0 do work complete at 17-06-15 16:42:52
Worker emp2 CountDownLatch count 2
Worker emp3 CountDownLatch count 2
Worker emp2 do work complete at 17-06-15 16:42:53
Worker emp3 do work complete at 17-06-15 16:42:53
Worker emp1 CountDownLatch count 0
Worker emp4 CountDownLatch count 0
Worker emp1 do work complete at 17-06-15 16:42:54
Worker emp4 do work complete at 17-06-15 16:42:54
均完成后的时间:17-06-15 16:42:54

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值