news 2026/6/15 21:28:19

Java CountDownLatch 代码示例及使用细节总结

作者头像

张小明

前端开发工程师

1.2k 24
文章封面图
Java CountDownLatch 代码示例及使用细节总结

CountDownLatch 极简入门示例

1. 基础使用示例

importjava.util.concurrent.CountDownLatch;publicclassSimpleCountDownLatchDemo{publicstaticvoidmain(String[]args)throwsInterruptedException{// 创建计数器,初始值为3CountDownLatchlatch=newCountDownLatch(3);// 创建3个线程for(inti=1;i<=3;i++){intthreadId=i;newThread(()->{try{Thread.sleep(threadId*1000L);System.out.println("线程"+threadId+" 完成任务");}catch(InterruptedExceptione){e.printStackTrace();}finally{// 计数器减1(必须执行)latch.countDown();}}).start();}// 主线程等待所有子线程完成System.out.println("主线程等待中...");latch.await();// 阻塞,直到计数器为0System.out.println("所有线程完成,主线程继续执行");}}

2. 带超时时间的示例

importjava.util.concurrent.CountDownLatch;importjava.util.concurrent.TimeUnit;publicclassTimeoutDemo{publicstaticvoidmain(String[]args)throwsInterruptedException{CountDownLatchlatch=newCountDownLatch(5);for(inti=1;i<=5;i++){newThread(()->{try{Thread.sleep(2000);// 每个线程执行2秒System.out.println(Thread.currentThread().getName()+" 完成");}finally{latch.countDown();}}).start();}// 最多等待3秒booleansuccess=latch.await(3,TimeUnit.SECONDS);if(success){System.out.println("✓ 所有任务在规定时间内完成");}else{System.out.println("✗ 等待超时,仍有任务未完成");System.out.println("剩余计数: "+latch.getCount());}}}

3. 实用场景示例:比赛起跑

importjava.util.concurrent.CountDownLatch;publicclassRaceDemo{publicstaticvoidmain(String[]args)throwsInterruptedException{intrunnerCount=4;CountDownLatchreadyLatch=newCountDownLatch(runnerCount);CountDownLatchstartLatch=newCountDownLatch(1);CountDownLatchfinishLatch=newCountDownLatch(runnerCount);// 运动员线程for(inti=1;i<=runnerCount;i++){intrunnerId=i;newThread(()->{try{// 1. 准备就绪Thread.sleep((long)(Math.random()*1000));System.out.println("运动员"+runnerId+" 准备就绪");readyLatch.countDown();// 2. 等待发令枪响startLatch.await();System.out.println("运动员"+runnerId+" 起跑!");// 3. 跑步Thread.sleep((long)(Math.random()*3000));System.out.println("运动员"+runnerId+" 到达终点");}catch(InterruptedExceptione){e.printStackTrace();}finally{finishLatch.countDown();}}).start();}// 裁判线程readyLatch.await();// 等待所有运动员就绪System.out.println("\n所有运动员准备就绪,比赛开始!\n");Thread.sleep(1000);// 准备时间startLatch.countDown();// 发令枪响finishLatch.await();// 等待所有运动员完成System.out.println("\n比赛结束!");}}

4. 最简单的单线程等待示例

importjava.util.concurrent.CountDownLatch;publicclassSimplestDemo{publicstaticvoidmain(String[]args)throwsInterruptedException{// 只有一个任务需要等待CountDownLatchlatch=newCountDownLatch(1);newThread(()->{try{Thread.sleep(2000);System.out.println("后台任务执行完成");}finally{latch.countDown();// 必须放在finally中}}).start();System.out.println("主线程等待中...");latch.await();System.out.println("主线程继续执行");}}

5. 常用方法速查表

方法说明示例
CountDownLatch(int count)创建计数器new CountDownLatch(5)
await()等待计数器归零latch.await()
await(timeout, unit)带超时等待latch.await(3, TimeUnit.SECONDS)
countDown()计数器减1latch.countDown()
getCount()获取当前计数值latch.getCount()

核心要点总结

  1. 初始化new CountDownLatch(N)- 创建N个任务的计数器
  2. 等待latch.await()- 主线程等待
  3. 完成latch.countDown()- 每个任务完成后调用
  4. 必须countDown()必须放在finally
  5. 建议:使用带超时的await()避免永久阻塞

记住:一次性的,用完即弃,不能重置重用。

版权声明: 本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若内容造成侵权/违法违规/事实不符,请联系邮箱:809451989@qq.com进行投诉反馈,一经查实,立即删除!
网站建设 2026/6/15 11:47:07

YOLOv8 PR曲线生成与分析方法

YOLOv8 PR曲线生成与分析方法 在智能监控系统部署过程中&#xff0c;一个常见的挑战是&#xff1a;模型明明在训练集上表现优异&#xff0c;却在真实场景中频繁漏检行人或误识背景为车辆。这种“纸上谈兵”式的性能假象&#xff0c;暴露出传统准确率指标在目标检测任务中的局限…

作者头像 李华
网站建设 2026/6/15 11:44:52

Dify 1.11.1补丁上线:如何在30分钟内完成安全升级并验证防护效果

第一章&#xff1a;Dify 1.11.1 安全补丁升级Dify 1.11.1 版本发布了一项关键的安全补丁&#xff0c;旨在修复此前版本中发现的身份验证绕过漏洞和敏感信息泄露问题。该更新适用于所有部署在公网环境中的 Dify 实例&#xff0c;建议系统管理员立即执行升级操作以保障服务安全。…

作者头像 李华
网站建设 2026/6/15 11:51:19

YOLOv8训练时出现CUDA Out of Memory怎么办?

YOLOv8训练时出现CUDA Out of Memory怎么办&#xff1f; 在深度学习项目中&#xff0c;尤其是使用YOLOv8这类高性能目标检测模型进行训练时&#xff0c;你有没有遇到过这样的场景&#xff1a;刚启动训练脚本&#xff0c;几秒钟后突然弹出一条红色错误信息——CUDA out of memor…

作者头像 李华
网站建设 2026/6/15 11:50:23

利用YOLOv8提升企业AI研发效率的五大优势

利用YOLOv8提升企业AI研发效率的五大优势 在智能制造工厂的质检线上&#xff0c;一台搭载摄像头的设备正以每分钟数百帧的速度扫描电路板——微小的焊点缺陷、错位元件甚至肉眼难辨的裂纹&#xff0c;都被实时捕捉并标记。这样的场景背后&#xff0c;往往离不开一个高效而稳定的…

作者头像 李华
网站建设 2026/6/15 11:49:55

如何提高YOLOv8在小目标检测中的准确率?

如何提高YOLOv8在小目标检测中的准确率&#xff1f; 在智能监控、无人机巡检和遥感分析等实际应用中&#xff0c;我们常常需要从一张高空中拍摄的图像里找出几十米外的小型车辆&#xff0c;或是从密集的人群中定位每一个个体。这些“小目标”往往只占图像的几个像素点&#xff…

作者头像 李华
网站建设 2026/6/15 11:44:52

Agentic AI与RAG技术选型指南:从原理到实战,一文搞懂何时用、何时避

本文深入解析了Agentic AI与RAG两大AI技术的本质、适用场景及结合方式。Agentic AI的核心是自主决策循环&#xff0c;适合多步骤工作流&#xff1b;RAG虽强大但非万能&#xff0c;规模化后需Context Engineering优化。文章提供了清晰的技术选型决策树&#xff1a;静态知识库适合…

作者头像 李华