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);一旦超时,线程将不再阻塞,直接执行