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!
相关推荐
2601_962293799 分钟前
OCRmyPDF批处理脚本:使用Python自动化复杂OCR任务
python·自动化·批处理脚本·ocrmypdf·ocr任务
Java后端的Ai之路1 小时前
20、Python - 备忘录模式
开发语言·人工智能·python·外观模式·备忘录模式
2601_962077712 小时前
基于Python与NLP的新闻事件信息抽取实战:从NER到时空标准化
python·nlp·transformers·spacy·新闻事件抽取
JavaPub-rodert2 小时前
LangChain 从入门到 Agent 实战:用 Python 搭建一个真正能调用工具和知识库的 AI 助手
人工智能·python·langchain
郝学胜-神的一滴3 小时前
Qt 高级编程 045:坐标体系深度实战
开发语言·c++·windows·python·qt·程序人生
m0_380743874 小时前
给 OpenAI API 调用加上模型切换:GPT-5.1 和 Codex 的配置实践
人工智能·python·gpt
2601_962297484 小时前
在python3中、下列输出变量a的正确写法是_2020超星大数据Python免费答案
数据结构·python·算法·编程·字符串操作
“AI国潮设计-小江”4 小时前
Python实战 | SDXL精准控制“普宁英歌舞×星空蛋糕”IP落地,附核心Prompt与商用授权思路
开发语言·人工智能·python·prompt·aigc
公爵爱学习4 小时前
无人机视觉识别前序-Linux-YOLO安装
python·yolo·计算机视觉·conda·无人机
2601_962295334 小时前
使用python实现一个浏览器自动化的脚本
python·脚本·rpa·浏览器自动化·操作