CountDownLatch:
Allows one or more threads to wait for other threads to complete operations.
CountDownLatch
Receives a int
type parameter indicating the number of worker threads to wait.
method:
method | illustrate |
await() | Make the current thread enter the synchronization queue and wait until latch the value is reduced 0 or the current thread is interrupted, the current thread will be awakened. |
await(long timeout, TimeUnit unit) | await() with timeout |
countDown() | Decrement latch the value 1 . If it is reduced , all threads 0 waiting on this will be awakened .latch |
getCount() | The value obtained latch . |
Code example:
//创建线程池,线程池的核心数可根据业务场景进行动态调整
ExecutorService executorService = Executors.newFixedThreadPool(10);
//如果有n个线程,那么就指定CountDownLatch 的计数器为 n
final CountDownLatch latch = new CountDownLatch(10);
for (int j = 0; j <10 ; j++) {
executorService.execute(()->{
log.info("子线程 start time:{},线程名称:{}", DateUtil.now(),Thread.currentThread().getName());
//此处是需要执行的业务操作
log.info("子线程 end time:{},线程名称:{}", DateUtil.now(),Thread.currentThread().getName());
//当前线程调用此方法,则计数器减一
latch.countDown();
});
}
try {
//主线程调用此方法,直到计数器的数值为0,主线程才开始处理
latch.await();
log.info("所有子线程执行完毕,主线程继续执行");
} catch (InterruptedException e) {
e.printStackTrace();
}
//销毁线程池
executorService.shutdown();
Article summary:
CountDownLatch has two main methods:
countDown() and await().
countDown() method: used to decrement the counter by one, which is usually called by the thread executing the task;
await() method: puts the thread calling this method in a waiting state, which is usually called by the main thread.
What needs to be noted here is that the countDown() method does not stipulate that a thread can only call it once. When the same thread calls the countDown() method multiple times, the counter will be decremented by one each time; in addition, the await() method does not It is stipulated that only one thread can execute this method. If multiple threads execute the await() method at the same time, then these threads will be in a waiting state and share the same lock in shared mode.