Java并发包工具类CountDownLatch的应用详解
CountDownLatch概述
CountDownLatch是java.util.concurrent包中提供的一个并发工具类,常用于控制多个线程等待一组事件的发生,直到所有的线程都达到某个状态后才能同时执行。
在CountDownLatch中,需要设定一个计数器,该计数器初始值为线程的数量,每个线程完成任务时都会使计数器减1,当计数器的值为0时,就说明所有的线程都已经完成了任务,这时等待中的线程可以开始执行。
CountDownLatch的使用场景
CountDownLatch常用于多线程任务协同处理的场景,例如:等待多个线程全部完成某件事情再执行下一步操作,等待多个线程都到达某个状态才能同时执行下一步操作,等待多个线程用完某个资源才能释放这个资源等。
CountDownLatch使用注意事项
- CountDownLatch一旦被初始化之后不能重新设置计数器的值。
- CountDownLatch计数器的值必须大于等于0,当计数器的值为0时,所有等待线程才能继续执行。
- CountDownLatch不支持中途增加或减少计数器的值,也不支持重置计数器的值。
CountDownLatch示例1-等待多个线程完成任务
import java.util.concurrent.CountDownLatch;
public class CountDownLatchDemo1 {
public static void main(String[] args) {
int N = 5;
final CountDownLatch latch = new CountDownLatch(N);
for (int i = 0; i < N; i++) {
new Thread(() -> {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName() + " finished");
latch.countDown(); // 计数器减1
}).start();
}
// 等待计数器变为0
try {
latch.await();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("All threads finished");
}
}
代码输出如下:
Thread-0 finished
Thread-1 finished
Thread-2 finished
Thread-3 finished
Thread-4 finished
All threads finished
在这个例子中,主线程通过CountDownLatch等待5个子线程都执行完毕之后执行。
CountDownLatch示例2-线程协作同步
import java.util.concurrent.CountDownLatch;
public class CountDownLatchDemo2 {
private static CountDownLatch startLatch = new CountDownLatch(1);
private static CountDownLatch endLatch = new CountDownLatch(5);
public static void main(String[] args) throws InterruptedException {
for (int i = 0; i < 5; i++) {
new Thread(() -> {
try {
System.out.println(Thread.currentThread().getName() + " waiting for startLatch");
startLatch.await();
System.out.println(Thread.currentThread().getName() + " started");
Thread.sleep(1000);
System.out.println(Thread.currentThread().getName() + " finished");
endLatch.countDown();
} catch (InterruptedException e) {
e.printStackTrace();
}
}).start();
}
Thread.sleep(1000);
startLatch.countDown();
// 等待所有线程执行完毕
endLatch.await();
System.out.println("All threads finished");
}
}
代码输出如下:
Thread-0 waiting for startLatch
Thread-4 waiting for startLatch
Thread-2 waiting for startLatch
Thread-1 waiting for startLatch
Thread-3 waiting for startLatch
Thread-1 started
Thread-0 started
Thread-2 started
Thread-4 started
Thread-3 started
Thread-1 finished
Thread-0 finished
Thread-2 finished
Thread-4 finished
Thread-3 finished
All threads finished
在这个例子中,5个线程竞争startLatch信号,只有当startLatch计数器为0时,所有线程才能开始执行;5个线程完成任务后,会将endLatch的计数器减1,当endLatch计数器为0时,主线程再继续执行。这个例子展示了CountDownLatch在多个线程协作同步的场景中的应用。
本站文章如无特殊说明,均为本站原创,如若转载,请注明出处:Java并发包工具类CountDownLatch的应用详解 - Python技术站