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

猜你喜欢

转载自blog.csdn.net/dam454450872/article/details/79959214