7.2J.U.C值AQS-CountDownLatch

初始化时指定一个计数值,调用await()方法的线程将会被阻塞,直到其他线程调用使用countDown()方法将计数值减为0才继续执行

package com.moluo.concurrency.aqs;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class CountDownLatchExample {

    private static final int THREAD_COUNT =200;

    public static void main(String[] args) throws InterruptedException {
        ExecutorService executorService= Executors.newCachedThreadPool();

        CountDownLatch countDownLatch=new CountDownLatch(THREAD_COUNT);
        
        for (int i=0;i<THREAD_COUNT;i++){
            final int index=i;
            executorService.execute(()->{
                try {
                    test(index);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }finally {
                    countDownLatch.countDown();
                }
            });
        }
        countDownLatch.await();
        System.out.println("finish");
        executorService.shutdown();
    }

    private static void test(int threadNum) throws InterruptedException {
        Thread.sleep(100);
        System.out.println(threadNum);
        Thread.sleep(100);
    }
}

注意:countDownLatch.await()方法可以指定时间,如countDownLatch.await(10, TimeUnit.MICROSECONDS);一旦超时,线程将不再阻塞,直接执行

Last updated

Was this helpful?