CountDownLatch如何使用?
16lz
2021-01-22
CountDownLatch 可以起到发令枪的作用,JDK 1.5 开始提供
用 CountDownLatch 实现并发访问,在写测试工具时希望达到某条件后,所有线程同时执行
也可以用 CountDownLatch 实现,某线程等待其他线程完成,进行最后的统一处理
代码如下:
package constxiong.interview;
import java.util.concurrent.CountDownLatch;
/**
* 测试使用100个线程,并发访问和等待多线程完成后处理
* @author ConstXiong
*/
public class TestCountDownLatch2 {
private static CountDownLatch cdl = new CountDownLatch(100);
private static int count = 0;
public static void main(String[] args) {
testConcurrent();
// testDoAfterOtherThreadComplete();
}
/**
* 测试并发 do something...
*/
private static void testConcurrent() {
for (int i = 0; i < 100; i++) {
//启动线程
new Thread(() -> {
try {
//当发令枪计数未减到 0 之前线程都会在此阻塞
cdl.await();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName() + ":" + System.currentTimeMillis() + " do something...");
}).start();
//发令枪计数减 1
cdl.countDown();
}
}
//测试等待多线程完成后处理
private static void testDoAfterOtherThreadComplete() {
//启动 100 个线程,对 count 递增
for (int i = 0; i < 100; i++) {
new Thread(() -> {
count++;
//发令枪计数减 1
cdl.countDown();
}).start();
}
try {
cdl.await();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("main thread print count : " + count);
}
}
更多相关文章
- Redis为什么又引入了多线程?作者也逃不过“真香定理”?
- 详解第三种创建线程的方式-Callable接口
- java线程相关面试题(第一版)
- Java线程之线程的调度-让步
- java中的几个线程池的使用
- (不谈废话,只有干货)解决线程间协作问题的工具类Exchanger详解
- 一文看懂 Node.js 中的多线程和多进程[每日前端夜话0x107]
- 如何停止一个线程池?