一、CountDownLatch简介
CountDownLatch是java.util.concurrent包中的一个同步辅助类,它允许一个或多个线程一直等待,直到其他线程的操作执行完后再执行。它是一个典型的多线程计数器,可以指定一个数字,每调用一次countDown()方法,这个数字就减一,所有线程都可以通过await()方法阻塞自己,直到这个数字减为0,所有等待线程才会被唤醒。
二、使用步骤
1、创建CountDownLatch对象,指定计数器的初始值;
CountDownLatch latch = new CountDownLatch(10);
2、在需要等待的线程中调用await()方法,阻塞当前线程;
latch.await();
3、在其他线程中,调用countDown()方法,计数器值减一;
latch.countDown();
4、当计数器值减为0时,等待的线程会被唤醒继续执行。
三、示例代码
下面的示例代码演示了如何使用CountDownLatch,该示例有两个线程,一个线程负责等待,另一个线程负责计数,当计数器值减为0时,等待线程会被唤醒继续执行。
public class CountDownLatchTest {
public static void main(String[] args) {
CountDownLatch latch = new CountDownLatch(10);
Thread thread1 = new Thread(new CountDownLatchThread(latch));
Thread thread2 = new Thread(new CountDownLatchThread2(latch));
thread1.start();
thread2.start();
}
}
class CountDownLatchThread implements Runnable {
private CountDownLatch latch;
public CountDownLatchThread(CountDownLatch latch) {
this.latch = latch;
}
@Override
public void run() {
try {
System.out.println("线程" + Thread.currentThread().getName() + "正在执行");
Thread.sleep(3000);
System.out.println("线程" + Thread.currentThread().getName() + "执行完毕");
latch.countDown();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
class CountDownLatchThread2 implements Runnable {
private CountDownLatch latch;
public CountDownLatchThread2(CountDownLatch latch) {
this.latch = latch;
}
@Override
public void run() {
try {
latch.await();
System.out.println("线程" + Thread.currentThread().getName() + "继续执行");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}