CountDownLatch-等待一個執行緒池執行完所有執行緒
阿新 • • 發佈:2022-03-28
- 建立一個執行緒池 threadPoolExecutor 執行緒數量為threadCount,
- 執行methodA()方法,threadCount次
- 等待執行緒池的執行緒全部執行完,即latch為0
- shutdown()執行緒池
@Test public void test(int threadCount) { ExecutorService threadPoolExecutor = new ThreadPoolExecutor(
threadCount/2,
threadCount, 1L, TimeUnit.SECONDS,new LinkedBlockingQueue<>(threadCount), Executors.defaultThreadFactory(), new ThreadPoolExecutor.AbortPolicy()); CountDownLatch latch = new CountDownLatch(threadCount); //迴圈執行methodA()方法 for (int count = threadCount; count > 0; count--) { threadPoolExecutor.submit(()-> { try { methodA( ); } catch (Exception e) { log.error(e.getMessage(), e); } finally { latch.countDown(); } }); } //阻塞當前主執行緒,直到latch等於0 try{ //阻塞當前執行緒,直到計數器的值為0 latch.await(); } catch (InterruptedException e) { e.printStackTrace(); } //關閉執行緒池 threadPoolExecutor.shutdown(); }