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

[java] 控制三个线程按顺序交替输出数字1、2、3

控制三个线程按顺序交替输出数字1、2、3

使用synchronized和wait/notify机制实现三个线程交替输出数字1、2、3。通过共享锁对象lock控制线程同步,currentThreadNum变量指示当前应执行的线程。每个线程在print方法中循环等待轮到自己执行,输出对应数字后唤醒其他线程,并按1→2→3→1的顺序切换执行权。主方法创建三个线程分别调用printOne()、printTwo()和printThree(),实现交替输出指定次数的数字序列。程序展示了多线程间的精确协调控制。

public class AlternateOutput {private static final Object lock = new Object();private static volatile int currentThreadNum = 1;private static final int count = 20;private static void runTask(int currentThreadNum, int nextThreadNum, String output) {for (int i = 0; i < count; i++) {synchronized (lock) {while (AlternateOutput.currentThreadNum != currentThreadNum) {try {lock.wait();} catch (InterruptedException e) {Thread.currentThread().interrupt();return;}}System.out.print(output);AlternateOutput.currentThreadNum = nextThreadNum;lock.notifyAll();}}}public static void main(String[] args) {Thread t1 = new Thread(() -> {runTask(1, 2, "1");});t1.start();Thread t2 = new Thread(() -> {runTask(2, 3, "2");});t2.start();Thread t3 = new Thread(() -> {runTask(3, 1, "3");});t3.start();// 确保主线程等待所有子线程完成执行后才结束,避免主线程提前退出导致子线程被强制终止try {t1.join();t2.join();t3.join();} catch (InterruptedException e) {Thread.currentThread().interrupt();}}
}
http://www.dtcms.com/a/353328.html

相关文章:

  • 【新版发布】Apache DolphinScheduler 3.3.1 正式上线:更稳、更快、更安全!
  • TensorFlow 面试题及详细答案 120道(21-30)-- 模型构建与神经网络
  • 数据结构:创建堆(或者叫“堆化”,Heapify)
  • 增强CD47检查点免疫治疗:高通量发现增强巨噬细胞吞噬作用的小分子协同剂
  • nestjs 连接redis
  • HIVE的Window functions窗口函数【一】
  • 手写题(面试)
  • LeetCode算法日记 - Day 24: 颜色分类、排序数组
  • LeetCode - 155. 最小栈
  • Python Imaging Library (PIL) 全面指南:PIL基础入门-跨平台安装与环境配置
  • Redis 数据结构
  • Linex系统网络管理(二)
  • 【yocto】Yocto Project 核心:深入了解.inc文件
  • Java中使用Spring Boot+Ollama构建本地对话机器人
  • Maven 依赖传递与排除基础逻辑
  • Astah UML 中,状态机(State Machine)的建模最合适使用「UML 状态图(State Diagram)」
  • 轻量级自动驾驶多视图视觉问答模型-EM-VLM4AD
  • 鸿蒙HarmonyOS状态管理装饰器详解
  • perccli 工具
  • 鸿蒙网络编程系列62-仓颉版使用Request部件上传多个文件到服务端
  • 华中科大联手小米推出ReCogDrive:自动驾驶迎来“认知革命”!
  • 零基础-力扣100题从易到难详解(持续更新)
  • 化学分析原理与算法、数据库。
  • 20250826的学习笔记
  • TDengine IPv6 支持用户手册
  • 盛大启幕!融智兴科技亮相 IOTE 2025 深圳国际物联网展
  • Mysql——调优
  • 从PostgreSQL到人大金仓(KingBase)数据库迁移实战:Spring Boot项目完整迁移指南
  • Python常见设计模式2: 结构型模式
  • jenkins集成liquibase