当前位置: 首页 > article >正文

CyclicBarrier使用案例

 CyclicBarrier使用案例


/**
 * CyclicBarrier使用案例,线程执行任务完成后会停留在await(),
 * 直到所有线程执行任务完毕,才会被放行;
 * 接着就会继续执行其他的任务
 */
public class CyclicBarrierExample {
    public static void main(String[] args) {
        int numThreads = 3;
        CyclicBarrier barrier = new CyclicBarrier(numThreads, () -> {
            System.out.println("All threads have reached the barrier. Starting the next phase.");
        });

        for (int i = 0; i < numThreads; i++) {
            Thread worker = new Thread(new Worker(barrier, "Worker-" + i));
            worker.start();
        }
    }

    static class Worker implements Runnable {
        private CyclicBarrier barrier;
        private String workerName;

        public Worker(CyclicBarrier barrier, String workerName) {
            this.barrier = barrier;
            this.workerName = workerName;
        }

        @Override
        public void run() {
            System.out.println(LocalDateTime.now().format(DateTimeFormatter.ofPattern("hh:mm:ss")) + " Worker " + workerName + " is working");
            try {
                Thread.sleep((long) (Math.random() * 2000)); // 模拟不同的工作时间
                System.out.println(LocalDateTime.now().format(DateTimeFormatter.ofPattern("hh:mm:ss")) + " Worker " + workerName + " has reached the barrier");
                barrier.await(); // 等待所有线程到达屏障
                System.out.println(LocalDateTime.now().format(DateTimeFormatter.ofPattern("hh:mm:ss")) + " Worker " + workerName + " is continuing to work");
            } catch (InterruptedException | BrokenBarrierException e) {
                e.printStackTrace();
            }
        }
    }
}

输出结果

12:45:40 Worker Worker-1 is working
12:45:40 Worker Worker-2 is working
12:45:40 Worker Worker-0 is working
12:45:40 Worker Worker-0 has reached the barrier
12:45:40 Worker Worker-1 has reached the barrier
12:45:42 Worker Worker-2 has reached the barrier
All threads have reached the barrier. Starting the next phase.
12:45:42 Worker Worker-2 is continuing to work
12:45:42 Worker Worker-0 is continuing to work
12:45:42 Worker Worker-1 is continuing to work

Process finished with exit code 0


http://www.kler.cn/a/134719.html

相关文章:

  • 如何在手机上完整下载B站视频并保存到相册?
  • 【C#设计模式(4)——构建者模式(Builder Pattern)】
  • 四:HTTP的诞生:它解决了哪些网络通信难题?
  • ARM架构中断与异常向量表机制解析
  • Ubuntu 的 ROS 操作系统安装与测试
  • StructuredStreaming (一)
  • ⑩⑥ 【MySQL】详解 触发器TRIGGER,协助 确保数据的完整性,日志记录,数据校验等操作。
  • 微服务学习|Nacos配置管理:统一配置管理、配置热更新、配置共享、搭建Nacos集群
  • 2021年3月青少年软件编程(Python)等级考试试卷(一级)
  • ckplayer自己定义风格播放器的开发记录
  • SaleSmartly新增AI意图识别触发器!让客户享受更精准的自动化服务
  • C++sqrt函数题目
  • 聊一聊小程序单聊页面构思
  • 【广州华锐互动】VR可视化政务服务为公众提供更直观、形象的政策解读
  • hadoop、hive、DBeaver的环境搭建及使用
  • CorelDraw2024(CDR)- 矢量图制作软件介绍
  • CentOS安装nodejs
  • 奇瑞金融:汽车金融行业架构设计
  • Modbus转Profinet网关在金银精炼控制系统中应用案例
  • 一步一步教你如何在Windows 10上使用Java,包括下载、安装和配置等
  • 系列六、多线程集合不安全
  • 开发《星球大战》小游戏的意义
  • AWS云服务器EC2实例实现ByConity快速部署
  • Python大数据之linux学习总结——day09_hive调优
  • 本地jar导入maven
  • 汇编层面有三个主要的操作对象