Java中虽然提供了synchronized关键字对临界区进行线程同步访问,但是基于synchronized很难正确地编写同步代码,而倒计时门闩可以让一条或多条线程在“门口”一直等待,直到门闩的计数变量为0,线程才可以继续执行。
组成
类java.util.concurrent.CountDownLatch实现了倒计时门闩同步器,它是由一个计数变量和两个操作数组成的,这两个操作分别是“导致一条线程等待直到计数变为0”以及“递减计数变量”
主要方法
CountDownLatch(int count):count是计数个数,当count的值是负数时,会抛出Exception
void await():除非线程被中断,否则强制调用线程一直等到计数倒数到0.中断时会抛出Exception
void countDown():递减计数,当计数降至0时,释放所有等待线程。当该方法被调用时count已经为0,那么 什么也不会发生
long getCount():返回当前的计数
示例程序
public class CountDownLatchDemo {
public static void main(String[] args) {
CountDownLatch countDownLatch = new CountDownLatch(3);
Runnable runnable = new Runnable() {
@Override
public void run() {
System.out.print(Thread.currentThread() + ": in this thread latch count is " + countDownLatch.getCount() + "\n");
countDownLatch.countDown();
System.out.print(Thread.currentThread() +": after count down, latch count is " + countDownLatch.getCount() + "\n");
}
};
ExecutorService executorService = Executors.newFixedThreadPool(3);
System.out.print("before latch await\n");
for (int i = 0; i < 3; i ++) {
executorService.execute(runnable);
}
try {
countDownLatch.await();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.print("main thread work again\n");
}
}
在这个示例中,有三个子线程和一个主线程,主线程调用await方法之后一直等待,直到倒计时门闩中的计数变量变为0才继续执行,结果如下:
before latch await
Thread[pool-1-thread-2,5,main]: in this thread latch count is 3
Thread[pool-1-thread-1,5,main]: in this thread latch count is 3
Thread[pool-1-thread-2,5,main]: after count down, latch count is 2
Thread[pool-1-thread-3,5,main]: in this thread latch count is 3
Thread[pool-1-thread-1,5,main]: after count down, latch count is 1
Thread[pool-1-thread-3,5,main]: after count down, latch count is 0
main thread work again
这里需要注意的是,并不是每次都会先打印子线程中的信息,可能会出现在子线程执行完countDown()方法之后,countLatchDown中的计数变量已经为0,主线程已经可以执行,这时cpu先执行了主线程中的print语句,之后再去执行子线程中的print语句。