Java并发编程同步器CountDownLatch怎么用
导读:本文共2003字符,通常情况下阅读需要7分钟。同时您也可以点击右侧朗读,来听本文内容。按键盘←(左) →(右) 方向键可以翻页。
摘要: CountDownLatch在日常开发中经常会遇到需要在主线程中开启多个线程去并行执行任务,并且主线程需要等待所有子线程执行完毕后再进行汇总的场景。在 CountDownLatch 出现之前般都使用线程的join()方法来实现这一点,但是 join 方法不够灵活,不能够满足不同场景的需要,所以 JDK 开发组提供了 CountDownLatch 这个类,我们前面... ...
目录
(为您整理了一些要点),点击可以直达。CountDownLatch
在日常开发中经常会遇到需要在主线程中开启多个线程去并行执行任务,并且主线程需要等待所有子线程执行完毕后再进行汇总的场景。在 CountDownLatch 出现之前般都使用线程的join()方法来实现这一点,但是 join 方法不够灵活,不能够满足不同场景的需要,所以 JDK 开发组提供了 CountDownLatch
这个类,我们前面介绍的例子使用 CoumtDownLatch
会更优雅。
使用CountDownLatch 的代码如下:
packageLockSupportTest;importjava.util.concurrent.CountDownLatch;publicclassJoinCountDownLatch{privatestaticvolatileCountDownLatchcountDownLatch=newCountDownLatch(2);publicstaticvoidmain(String[]args)throwsInterruptedException{ThreadthreadOne=newThread(newRunnable(){@Overridepublicvoidrun(){try{Thread.sleep(1000);System.out.println("childthreadOneover!");}catch(InterruptedExceptione){e.printStackTrace();}finally{countDownLatch.countDown();}}});ThreadthreadTwo=newThread(newRunnable(){@Overridepublicvoidrun(){try{Thread.sleep(1000);System.out.println("childthreadOneover!");}catch(InterruptedExceptione){e.printStackTrace();}finally{countDownLatch.countDown();}}});threadOne.start();threadTwo.start();System.out.println("waitallchildthreadover!!!");countDownLatch.await();System.out.println("allchildthreadover!");}}
在如上代码中,创建了一个 CountDownLatch
实例,因为有两个子线程所以构造函数的传参为2。主线程调用countDownLatch.await()
方法后会被阻塞。子线程执行完毕后调用 countDownLatch.countDown()
方法让 countDownLatch 内部的计数器减1,所有子线程执行完毕并调用 countDown()方法后计数器会变为0,这时候主线程的await()方法才会返回。其实上面的代码还不够优雅,在项目实践中一般都避免直接操作线程,而是使用 ExceutorService线程池来管理,使用ExcsuIwsnise时传递的参数是 Runable 或者 Callable对象,这时候你没有办法直接调用这些线程的join()方法,这就需要选择使用CountDownLatch
了。
将上面的代码修改为:
packageLockSupportTest;importjava.util.concurrent.CountDownLatch;importjava.util.concurrent.Executor;importjava.util.concurrent.ExecutorService;importjava.util.concurrent.Executors;publicclassJoinCountDownLatch3{privatestaticvolatileCountDownLatchcountDownLatch=newCountDownLatch(2);publicstaticvoidmain(String[]args)throwsInterruptedException{ExecutorServiceexecutorService=Executors.newFixedThreadPool(2);executorService.submit(newRunnable(){@Overridepublicvoidrun(){try{Thread.sleep(1000);System.out.println("childthreadOneover!");}catch(InterruptedExceptione){e.printStackTrace();}finally{countDownLatch.countDown();}}});executorService.submit(newRunnable(){@Overridepublicvoidrun(){try{Thread.sleep(1000);System.out.println("childthreadTwoover!");}catch(InterruptedExceptione){e.printStackTrace();}finally{countDownLatch.countDown();}}});System.out.println("waitallchildthreadover!!!");countDownLatch.await();System.out.println("allchildthreadover!");executorService.shutdown();}}
</div> <div class="zixun-tj-product adv-bottom"></div> </div> </div> <div class="prve-next-news">
Java并发编程同步器CountDownLatch怎么用的详细内容,希望对您有所帮助,信息来源于网络。