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!
相关推荐
眼眸流转18 分钟前
MCP学习笔记
python·uv·pydantic·mcp
千禧皓月23 分钟前
huggingface-cli下载数据集和模型
python
DREAM依旧37 分钟前
本地微调的Ollama模型部署到Dify平台上
人工智能·python
小陈phd38 分钟前
langGraph从入门到精通(九)——基于LangGraph构建具备多工具调用与自动化摘要能力的智能 Agent
人工智能·python·langchain
一晌小贪欢38 分钟前
Python 对象的“Excel 之旅”:使用 openpyxl 高效读写与封装实战
开发语言·python·excel·表格·openpyxl·python办公·读取表格
【赫兹威客】浩哥39 分钟前
【赫兹威客】Python解释器部署教程
python
代码or搬砖44 分钟前
Prompt(提示词工程)
人工智能·python·prompt
喵手1 小时前
Python爬虫零基础入门【第二章:网页基础·第3节】接口数据基础:JSON 是什么?分页是什么?
爬虫·python·python爬虫实战·python爬虫工程化实战·python爬虫零基础入门·接口数据基础·爬虫json
2501_944526421 小时前
Flutter for OpenHarmony 万能游戏库App实战 - 关于页面实现
android·java·开发语言·javascript·python·flutter·游戏
开开心心_Every1 小时前
手机端课程表管理工具:支持课程导入自定义
python·游戏·微信·django·pdf·excel·语音识别