作用
CountDownLatch,闭锁。能让线程等待其它线程完成个子的工作后再执行。
使用方法
CountDownLatch通过一个计数器来实现,计数器的初始值为初始任务的数量,每当完成一个任务后,计数器的值会减去1。当计数器到达0时候,表示所有任务完成,调用了CountDownLatch.await()方法的线程就可以恢复执行。
应用场景
/**
* 演示CountDownLatch用法,
* 共5个初始化子线程,6个闭锁扣除点,扣除完毕后,主线程和业务线程才能继续执行
* Created by linshujie on 2022/3/26.
*/
public class UseCountDownLatch {
static CountDownLatch latch = new CountDownLatch(6);
/**
* 初始化线程
*/
private static class InitRunnable implements Runnable {
public void run() {
System.out.println("Thread_" + Thread.currentThread().getId()
+ " ready init work......");
latch.countDown();
for (int i = 0; i < 2; i++) {
System.out.println("Thread_" + Thread.currentThread().getId()
+ " ........continue do its work");
}
}
}
/**
* 业务线程等待latch的计数器为0完成
*/
private static class BusiRunnable implements Runnable {
public void run() {
try {
//业务线程工作
latch.await();
} catch (InterruptedException e) {
e.printStackTrace();
}
for (int i = 0; i < 3; i++) {
System.out.println("BusiRunnable_" + Thread.currentThread().getId()
+ " do business-----");
}
}
}
public static void main(String[] args) throws InterruptedException {
//start一个初始化线程
new Thread(new Runnable() {
public void run() {
SleepTools.ms(1);
System.out.println("Thread_" + Thread.currentThread().getId()
+ " ready init work step 1st......");
latch.countDown();
System.out.println("Thread_" + Thread.currentThread().getId()
+ " begin step 2nd.......");
SleepTools.ms(1);
System.out.println("Thread_" + Thread.currentThread().getId()
+ " ready init work step 2nd......");
latch.countDown();
}
}).start();
//start一个业务线程
new Thread(new BusiRunnable()).start();
//start 4个初始化线程
for (int i = 0; i < 4; i++) {
Thread thread = new Thread(new InitRunnable());
thread.start();
}
//主线程工作
latch.await();
System.out.println("Main do ites work........");
}
}
执行结果:
Thread_29 ready init work......
Thread_26 ready init work......
Thread_28 ready init work......
Thread_27 ready init work......
Thread_24 ready init work step 1st......
Thread_27 ........continue do its work
Thread_29 ........continue do its work
Thread_26 ........continue do its work
Thread_29 ........continue do its work
Thread_28 ........continue do its work
Thread_27 ........continue do its work
Thread_28 ........continue do its work
Thread_24 begin step 2nd.......
Thread_26 ........continue do its work
Thread_24 ready init work step 2nd......
Main do ites work........
BusiRunnable_25 do business-----
BusiRunnable_25 do business-----
BusiRunnable_25 do business-----
Class transformation time: 0.019353s for 148 classes or 1.307635135135135E-4s per class
Process finished with exit code 0
一张图表示:
版权声明:本文为Shujie_L原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。