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!
相关推荐
哥本哈士奇(aspnetx)3 小时前
Streamlit + LangChain 1.0 简单实现智能问答前后端
python·大模型
我一定会有钱4 小时前
斐波纳契数列、end关键字
python
小鸡吃米…5 小时前
Python 列表
开发语言·python
星依网络6 小时前
yolov5实现游戏图像识别与后续辅助功能
python·开源·游戏程序·骨骼绑定
大佐不会说日语~6 小时前
Spring AI Alibaba 的 ChatClient 工具注册与 Function Calling 实践
人工智能·spring boot·python·spring·封装·spring ai
2501_921649496 小时前
如何获取美股实时行情:Python 量化交易指南
开发语言·后端·python·websocket·金融
qq_448011166 小时前
python HTTP请求同时返回为JSON的异常处理
python·http·json
棒棒的皮皮6 小时前
【OpenCV】Python图像处理几何变换之翻转
图像处理·python·opencv·计算机视觉
CodeCraft Studio7 小时前
国产化PPT处理控件Spire.Presentation教程:使用Python将图片批量转换为PPT
python·opencv·powerpoint·ppt文档开发·ppt组件库·ppt api
五阿哥永琪7 小时前
Spring Boot 中自定义线程池的正确使用姿势:定义、注入与最佳实践
spring boot·后端·python