CountDownLatch 介绍

package com.karl.example;

import java.util.concurrent.CountDownLatch;

/**
 * Created by karl.
 */
public class CountDownLatchExample {
    public static class Task implements Runnable{
        private String name;
        private CountDownLatch latch;
        private Long timeToStart;

        public Task(String name, Long timeToStart, CountDownLatch latch){
            this.name = name;
            this.latch = latch;
            this.timeToStart = timeToStart;
        }

        @Override
        public void run() {
            try {
                Thread.sleep(timeToStart);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println( name + " is Up");
            latch.countDown(); //计数器减1

        }
    }

    public static void main(String[] args) {
        CountDownLatch latch = new CountDownLatch(3);
        Thread t1 = new Thread(new Task("Thread 1",1000L,latch));
        Thread t2 = new Thread(new Task("Thread 2",1000L,latch));
        Thread t3 = new Thread(new Task("Thread 3",1000L,latch));
        Thread t4 = new Thread(new Task("Thread 4",1000L,latch));
        Thread t5 = new Thread(new Task("Thread 5",1000L,latch));
        Thread t6 = new Thread(new Task("Thread 6",1000L,latch));
        t1.start();
        t2.start();
        t3.start();
        t4.start();
        t5.start();
        t6.start();
        try {
            latch.await();
            System.out.println("at least 3 thread startup,application is starting now");
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}

结果:

Thread 2 is Up
Thread 1 is Up
Thread 3 is Up
Thread 4 is Up
at least 3 thread startup,application is starting now
Thread 5 is Up
Thread 6 is Up
原文地址:https://www.cnblogs.com/zhonghan/p/5009902.html