简介
CountDownLatch常用于让多个线程并行执行和让线程等待其他线程完成之后再执行,提供了以下方法
方法 | 说明 |
---|---|
await() | 使当前线程进入同步队列进行等待,直到latch的值被减到0或者当前线程被中断,当前线程就会被唤醒。 |
await(long timeout, TimeUnit unit) | 带超时时间的await()。 |
countDown() | 使latch的值减1,如果减到了0,则会唤醒所有等待在这个latch上的线程。 |
getCount() | 获得latch的数值。 |
例子
测试并发时,等所有线程都启动好后再一起执行,例如测试1000个线程并行参与秒杀
public class CountDownLatchTest {
public static void main(String[] args) throws InterruptedException {
CountDownLatch c = new CountDownLatch(1);
for(int i = 0; i < 1000; i++) {
new Thread(() -> {
System.out.println(Thread.currentThread().getName() + "启动完成");
try {
c.await();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName() + "开始执行秒杀");
}, i + "号线程").start();
}
c.countDown();
}
}
有两个线程需要等其他三个线程都执行完在执行
public class CountDownLatchTest {
public static void main(String[] args) throws InterruptedException {
CountDownLatch c = new CountDownLatch(3);
for(int i = 0; i < 2; i++) {
new Thread(() -> {
try {
System.out.println(Thread.currentThread().getName() + "开始等待");
c.await();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName() + "执行完毕");
}, i + "号等待线程").start();
}
for(int i = 0; i < 3; i++) {
new Thread(() -> {
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName() + "执行完毕");
c.countDown();
}, i + "号线程").start();
}
}
}