Java并发编程同步器CountDownLatch怎么用(countdownlatch,java,开发技术)

时间:2024-05-05 21:58:53 作者 : 石家庄SEO 分类 : 开发技术
  • TAG :

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!");}}

Java并发编程同步器CountDownLatch怎么用

在如上代码中,创建了一个 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();}}

Java并发编程同步器CountDownLatch怎么用

 </div> <div class="zixun-tj-product adv-bottom"></div> </div> </div> <div class="prve-next-news">
本文:Java并发编程同步器CountDownLatch怎么用的详细内容,希望对您有所帮助,信息来源于网络。
上一篇:C++基于范围的for循环怎么使用下一篇:

6 人围观 / 0 条评论 ↓快速评论↓

(必须)

(必须,保密)

阿狸1 阿狸2 阿狸3 阿狸4 阿狸5 阿狸6 阿狸7 阿狸8 阿狸9 阿狸10 阿狸11 阿狸12 阿狸13 阿狸14 阿狸15 阿狸16 阿狸17 阿狸18