CountDownLatch 模拟高并发
// countdownlatch 模拟高并发
public static void main(String[] args) throws InterruptedException {
CountDownLatch cdl = new CountDownLatch(10);
for (int i = 0; i < 10; i++) {
int cnt = 0;
new Thread(()->{
try {
System.out.println("开始"+Thread.currentThread().getName());
// 程序等待,直至CountDownLatch的数归零
cdl.await();
System.out.println(Thread.currentThread().getName()+"执行"+ (cnt +1));
} catch (InterruptedException e) {
e.printStackTrace();
}
}).start();
}
Thread.sleep(5000);
for (int i = 0; i < 10; i++) {
// 将CountDownLatch的数减一
cdl.countDown();
}
}
执行结果:
开始Thread-1
开始Thread-2
开始Thread-0
开始Thread-3
开始Thread-4
开始Thread-5
开始Thread-6
开始Thread-7
开始Thread-8
开始Thread-9
Thread-2执行1
Thread-5执行1
Thread-7执行1
Thread-8执行1
Thread-4执行1
Thread-3执行1
Thread-0执行1
Thread-1执行1
Thread-9执行1
Thread-6执行1

浙公网安备 33010602011771号