CountDownLatch 流程与 thread.join() 方法类似
CountDownLatch 好比门栓
CountDownLatch latch = new CountDownLatch(number); // 门栓数量
latch.countDown(); // 倒数计算 CountDownLatch(number) 的 number - 1;
latch.getCount(); // 获取剩余门栓数量,当 latch.getCount()=0 时线程会自动唤醒
latch.await(); // 阻塞,等待 latch.getCount()=0 时开门,继续执行后面的操作...
import java.util.concurrent.CountDownLatch;
public class CountDownLatchDemo {
public static void main(String[] args) {
usingJoin(100);
System.err.println("===================================");
usingCountDownLatch(10, 10000);
}
private static void usingJoin(int threadNumber) {
Thread[] threads = new Thread[threadNumber];
for (int i = 0; i < threads.length; i++) {
threads[i] = new Thread(() -> System.out.println(Thread.currentThread().getName() + "线程冲呀..."));
}
System.err.println("线程开始运行");
for (int i = 0; i < threads.length; i++) threads[i].start();
System.err.println(" `当前的线程` 在主线程内 调用join方法," +
" `主线程` 会等待 `当前的线程` 运行完之后才会开始执行后续代码");
for (int i = 0; i < threads.length; i++) join(threads[i]);
System.err.println("end usingJoin 当前线程为:" + Thread.currentThread().getName());
}
private static void join(Thread thread) {
try {
thread.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
private static void usingCountDownLatch(int number, int threadNumber) {
Thread[] threads = new Thread[threadNumber];
CountDownLatch latch = new CountDownLatch(number);
System.out.println("栓上门, 满" + number + "个线程后 才能执行后面的操作,否则一直等待...");
for (int i = 0; i < threads.length; i++) {
threads[i] = new Thread(() -> {
System.out.println(Thread.currentThread().getName() + "线程冲呀...");
latch.countDown();
});
}
System.out.println("线程开始运行");
for (int i = 0; i < threads.length; i++) {
threads[i].start();
if (latch.getCount() == 0) {
if (i + 1 == number) {
System.err.println("latch.getCount() 为0了,执行继续后面的操作....");
} else {
System.err.println("latch.getCount() 为0了,但是当前循环没有结束...");
}
}
}
await(latch);
System.err.println("end usingCountDownLatch");
}
private static void await(CountDownLatch latch) {
System.err.println("阻塞中...等待 latch.getCount()=0时,线程继续执行...");
try {
latch.await();
System.err.println("开门了... latch.getCount() 为0,开始执行后面的操作...");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}