CountDownLatch的简单用法

CountDownLatch类在java.util.concurrent(俗称juc)包下,一般用于一个任务需要等待多个线程执行的结果的情况下,是一个同步辅助类。

主要用到它的方法是

①构造器:设置计数器的数量

 public CountDownLatch(int count) {
        if (count < 0) throw new IllegalArgumentException("count < 0");
        this.sync = new Sync(count);
    }

②await():阻塞当前线程,等待计数器的数量变为0

public void await() throws InterruptedException {
        sync.acquireSharedInterruptibly(1);
    }

③countDown():计数器减一

    public void countDown() {
        sync.releaseShared(1);
    }

demo

package juc;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.concurrent.CountDownLatch;

public class CountDownLatchDemo {
    final static SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    public static void main(String[] args) throws InterruptedException {
        // 两个人比赛跑步
        CountDownLatch latch = new CountDownLatch(2);
        Runner runner1 = new Runner("博尔特", latch, 7000);
        Runner runner2 = new Runner("苏炳添", latch, 8000);
        runner1.start();
        runner2.start();
        // 等待两个运动员都跑完
        latch.await();
        System.out.println("运动员都跑完了,时间"+ sdf.format(new Date()));
    }

    static class Runner extends Thread{
        String runnerName;
        CountDownLatch latch;
        int runTime;
        public Runner(String runnerName,CountDownLatch latch,int runTime) {
            this.runnerName = runnerName;
            this.latch = latch;
            this.runTime = runTime;
        }

        public void run() {
            System.out.println(runnerName+" run begin at " +sdf.format(new Date()));
            // 开始跑步
            doRun();
            System.out.println(runnerName+" run end at " + sdf.format(new Date()));
            // 运动员跑步完成,计数器减一
            latch.countDown();
        }

        private void doRun() {
            try {
                Thread.sleep(runTime);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}

输出结果:

博尔特 run begin at 2018-04-16 12:56:15
苏炳添 run begin at 2018-04-16 12:56:15
博尔特 run end at 2018-04-16 12:56:22
苏炳添 run end at 2018-04-16 12:56:23
运动员都跑完了,时间2018-04-16 12:56:23

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值