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!
相关推荐
川石课堂软件测试27 分钟前
全链路Controller压测负载均衡
android·运维·开发语言·python·mysql·adb·负载均衡
喜欢吃豆38 分钟前
微调高级推理大模型(COT)的综合指南:从理论到实践
人工智能·python·语言模型·大模型·微调·强化学习·推理模型
喜欢吃豆1 小时前
从指令遵循到价值对齐:医疗大语言模型的进阶优化、对齐与工具集成综合技术白皮书
人工智能·python·语言模型·自然语言处理·大模型·强化学习·constitutional
Access开发易登软件1 小时前
Access调用Azure翻译:轻松实现系统多语言切换
后端·python·低代码·flask·vba·access·access开发
yumgpkpm1 小时前
CMP (类Cloudera) CDP7.3(400次编译)在华为鲲鹏Aarch64(ARM)信创环境中的性能测试过程及命令
大数据·hive·hadoop·python·elasticsearch·spark·cloudera
代码小菜鸡6662 小时前
java 常用的一些数据结构
java·数据结构·python
CodeCraft Studio3 小时前
Excel处理控件Aspose.Cells教程:使用 Python 将 HTML 转换为 Excel
python·html·excel·aspose·aspose.cells·html转excel
王中阳Go4 小时前
Python 的 PyPy 能追上 Go 的性能吗?
后端·python·go
Goboy4 小时前
控制仙术流程 - 抉择与循环的艺术
后端·python
麦麦大数据4 小时前
F024 vue+flask电影知识图谱推荐系统vue+neo4j +python实现
vue.js·python·flask·知识图谱·推荐算法·电影推荐