简介
概念
CountDownLatch允许一个或者多个线程去等待其他线程完成操作。
CountDownLatch接收一个int型参数,表示要等待的工作线程的个数。
当然也不一定是多线程,在单线程中可以用这个int型参数表示多个操作步骤。
方法
CountDownLatch 提供了一些方法:
方法    说明
await()    使当前线程进入同步队列进行等待,直到latch的值被减到0或者当前线程被中断,当前线程就会被唤醒。
await(long timeout, TimeUnit unit)    带超时时间的await()。
countDown()    使latch的值减1,如果减到了0,则会唤醒所有等待在这个latch上的线程。
getCount()    获得latch的数值。
| 方法 | 说明 | 
| await() | 使当前线程进入同步队列进行等待,直到latch的值被减到0或者当前线程被中断,当前线程就会被唤醒。 | 
| await(long timeout, TimeUnit unit) | 带超时时间的await()。 | 
| countDown() | 使latch的值减1,如果减到了0,则会唤醒所有等待在这个latch上的线程。 | 
| getCount() | 获得latch的数值。 | 
 
DEMO
线程池配置
| 12
 3
 4
 5
 6
 7
 8
 9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 
 | @Configurationpublic class DemoThreadPoolConfig {
 
 private static final AtomicInteger ATOMIC_INTEGER = new AtomicInteger(1);
 private static final AtomicInteger PLZDLX_ATOMIC_INTEGER = new AtomicInteger(1);
 
 private static final int CORE_POOL_SIZE = 4;
 
 private static final int PLZDLX_CORE_POOL_SIZE = 2;
 
 private static final int MAXIMUM_POOL_SIZE = 4;
 
 private static final int KEEP_ALIVE_TIME = 60;
 
 private static final int CAPACITY = 1000;
 
 
 
 
 
 
 
 @Bean("DemoExecutorService")
 public ExecutorService executorService() {
 return TtlExecutors.getTtlExecutorService(new ThreadPoolExecutor(
 Runtime.getRuntime().availableProcessors() * CORE_POOL_SIZE,
 Runtime.getRuntime().availableProcessors() * MAXIMUM_POOL_SIZE, KEEP_ALIVE_TIME, TimeUnit.SECONDS,
 new ArrayBlockingQueue<>(CAPACITY), r -> new Thread(r, "Thread-countDownLatch" + ATOMIC_INTEGER.getAndIncrement()),
 new MainRejectedExecutionHandler()));
 }
 }
 
 | 
使用线程池创建线程,并使用countDownLatch等待所有线程执行完毕
| 12
 3
 4
 5
 6
 7
 8
 9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 
 | @Resource(name = "DemoExecutorService")private ExecutorService DemoExecutorService;
 
 @Transactional(rollbackFor = Exception.class)
 public void batchAjqs(List<String> ids) {
 CountDownLatch countDownLatch = new CountDownLatch(ids.size());
 long start = System.currentTimeMillis();
 ids.forEach(id -> DemoExecutorService.execute(() -> {
 ResponseEntity<TestVO> res = DataBaseApi.selectByPrimaryKey(id);
 countDownLatch.countDown();
 }));
 try {
 countDownLatch.await();
 } catch (InterruptedException e) {
 log.warn("发生中断异常", e);
 Thread.currentThread().interrupt();
 }
 log.info("批量处理{}个线程共花费{} ms", ids.size(), (System.currentTimeMillis() - start));
 }
 
 | 
                
                
                
                
                
                
                
                
                
                
                
                
                
                
                
                
                
                
                
                
                
                
                
                
                
             
            
            
            
    
      
    
                
            
            
        
This is copyright.