一、什么是CountDownLatch CountDownLatch是一个同步工具类,它通过一个计数器来实现的,初始值为线程的数量。 每当一个线程完成了自己的任务,计数器的值就相应得减1。 当计数器
一、什么是CountDownLatch
CountDownLatch是一个同步工具类,它通过一个计数器来实现的,初始值为线程的数量。
每当一个线程完成了自己的任务,计数器的值就相应得减1。
当计数器到达0时,表示所有的线程都已执行完毕,然后在等待的线程就可以恢复执行任务。
二、方法详解
CountDownLatch 提供了一些方法:
方法
说明
await()
使当前线程进入同步队列进行等待,直到latch的值被减到0或者当前线程被中断,当前线程就会被唤醒。
await(long timeout, TimeUnit unit)
带超时时间的await()。
countDown()
使latch的值减1,如果减到了0,则会唤醒所有等待在这个latch上的线程。
getCount()
获得latch的数值。
三、CountDownLatch应用场景
1. 某个线程需要在其他n个线程执行完毕后再向下执行2. 多个线程并行执行同一个任务,提高响应速度
四、CountDownLatch代码示例
下面代码演示2个等待线程通过CountDownLatch去等待3个工作线程完成操作:
public class CountDownLatchTest {public static void main(String[] args) throws InterruptedException {
// 让2个线程去等待3个三个工作线程执行完成
CountDownLatch c = new CountDownLatch(3);
// 2 个等待线程
WaitThread waitThread1 = new WaitThread("wait-thread-1", c);
WaitThread waitThread2 = new WaitThread("wait-thread-2", c);
// 3个工作线程
Worker worker1 = new Worker("worker-thread-1", c);
Worker worker2 = new Worker("worker-thread-2", c);
Worker worker3 = new Worker("worker-thread-3", c);
// 启动所有线程
waitThread1.start();
waitThread2.start();
Thread.sleep(1000);
worker1.start();
worker2.start();
worker3.start();
}
}
/**
* 等待线程
*/
class WaitThread extends Thread {
private String name;
private CountDownLatch c;
public WaitThread(String name, CountDownLatch c) {
this.name = name;
this.c = c;
}
public void run() {
try {
// 等待
System.out.println(this.name + " wait...");
c.await();
System.out.println(this.name + " continue running...");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
/**
* 工作线程
*/
class Worker extends Thread {
private String name;
private CountDownLatch c;
public Worker(String name, CountDownLatch c) {
this.name = name;
this.c = c;
}
public void run() {
System.out.println(this.name + " is running...");
try {
Thread.sleep(2);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(this.name + " is end.");
c.countDown();
}
}
运行结果
wait-thread-1 wait...wait-thread-2 wait...
worker-thread-3 is running...
worker-thread-2 is running...
worker-thread-1 is running...
worker-thread-1 is end.
worker-thread-3 is end.
worker-thread-2 is end.
wait-thread-1 continue running...
wait-thread-2 continue running...
Process finished with exit code 0