python 3个线程轮流打印A、B、C

要实现 Python 中三个线程轮流打印 ABC 的效果,可以使用 threading 模块和 ConditionLock 来同步线程。以下是使用 Condition 的解决方案:

代码实现

python 复制代码
import threading

# 初始化条件变量
condition = threading.Condition()
current = 0  # 共享变量,用于标记当前线程应打印的字符

def print_char(char, thread_id):
    global current
    for _ in range(10):  # 打印 10 轮
        with condition:
            # 等待轮到当前线程打印
            while current != thread_id:
                condition.wait()
            print(char, end='', flush=True)  # 打印字符
            current = (current + 1) % 3  # 更新到下一个线程
            condition.notify_all()  # 唤醒其他线程

# 创建线程
threads = [
    threading.Thread(target=print_char, args=('A', 0)),
    threading.Thread(target=print_char, args=('B', 1)),
    threading.Thread(target=print_char, args=('C', 2)),
]

# 启动线程
for t in threads:
    t.start()

# 等待线程结束
for t in threads:
    t.join()

print("\nDone!")

代码说明

  1. Condition:

    • 用于线程间通信,确保线程按照 A -> B -> C 的顺序打印。
    • condition.wait():当前线程等待,直到其他线程调用 notify_all()
    • condition.notify_all():唤醒所有等待的线程。
  2. current 变量:

    • 用于记录当前应该打印的线程编号(0: A, 1: B, 2: C)。
    • 每打印一次后,更新为下一个线程的编号。
  3. 轮流打印:

    • 每个线程在条件满足时打印字符,打印后唤醒其他线程。
  4. 循环打印 10 次:

    • 可以通过调整循环次数(for _ in range(10))来控制打印轮数。

输出结果

程序运行后将输出类似以下内容:

复制代码
ABCABCABCABCABCABCABCABCABCABC
Done!
相关推荐
Hello world.Joey20 分钟前
数据挖掘入门-二手车交易价格预测
人工智能·python·数据挖掘·数据分析·conda·pandas
刘延林.24 分钟前
树莓5安装 PyCharm 进行python脚本开发
ide·python·pycharm
小洛~·~34 分钟前
多模态RAG与LlamaIndex——1.deepresearch调研
人工智能·python·深度学习·神经网络·chatgpt
q_q王1 小时前
‌FunASR‌阿里开源的语音识别工具
python·大模型·llm·语音识别
不学无术の码农2 小时前
《Effective Python》第1章 Pythonic 思维总结——编写优雅、高效的 Python 代码
开发语言·python
zhou1852 小时前
MySQL保姆级安装教程(附资源包+5分钟极速配置+环境变量调试技巧)
java·python·mysql·php
lczdyx2 小时前
PNG转ico图标(支持圆角矩形/方形+透明背景)Python脚本 - 随笔
图像处理·python
lgily-12253 小时前
常用的设计模式详解
java·后端·python·设计模式
陈苏同学3 小时前
MPC控制器从入门到进阶(小车动态避障变道仿真 - Python)
人工智能·python·机器学习·数学建模·机器人·自动驾驶
mahuifa3 小时前
python实现usb热插拔检测(linux)
linux·服务器·python