CountDownLatch是java.util.concurrent包中的类,它的作用是1个线程等待,多个线程唤醒此等待。
CountDownLatch cdl = new CountDownLatch(2);
通过构造方法声明CountDownLatch对象,2这个参数说明一共3个线程。1个线程执行时需要等待,其它的2个线程都进行唤醒操作之后前面的等待线程才能继续执行。
//在此等待阻塞
cdl.await();
//唤醒CountDownLatch的等待
cdl.countDown();
完整列子:
3个线程同时执行,当前两个线程执行完毕发出唤醒通知后,第三个线程才能执行完成。
public static void main(String[] args) {
CountDownLatch cdl = new CountDownLatch(2);
Thread t1 = new Thread(new Runnable() {
@Override
public void run() {
System.err.println("线程 " + Thread.currentThread().getName() + " 开始执行。。。");
try {
//实际工作中是进行一些业务处理
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
//唤醒线程
System.err.println("线程 " + Thread.currentThread().getName() + " 进行唤醒操作。。。");
cdl.countDown();
}
},"t1");
Thread t2 = new Thread(new Runnable() {
@Override
public void run() {
System.err.println("线程 " + Thread.currentThread().getName() + " 开始执行。。。");
try {
//实际工作中是进行一些业务处理
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
//唤醒线程
System.err.println("线程 " + Thread.currentThread().getName() + " 进行唤醒操作。。。");
cdl.countDown();
}
},"t2");
Thread t3 = new Thread(new Runnable() {
@Override
public void run() {
System.err.println("线程 " + Thread.currentThread().getName() + " 开始执行并等待其他线程全部唤醒后执行。。。");
try {
cdl.await();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.err.println("线程 " + Thread.currentThread().getName() + " 被其他线程唤醒,继续执行完毕");
}
},"t3");
t1.start();
t2.start();
t3.start();
}
结果及分析:
首先t1、t2、t3这三个线程同时执行,其中t3线程进行等待,t1线程内执行完后进行唤醒操作,然后t2线程进行唤醒操作,两个线程都进行唤醒操作后,t3线程开始执行。