Python:通过继承Thread类创建多线程并循环打印输出内容示例
以下是使用继承Thread类创建线程,并通过循环打印输出内容的示例代码: ```python import threading # 继承Thread类创建自定义线程类 class MyThread(threading.Thread): def run(self): for i in range(5): print('This is a thread:', self.getName(), 'Loop:', i) # 创建多个线程并启动 threads = [] for i in range(3): t = MyThread() threads.append(t) t.start() # 等待所有线程执行完毕 for t in threads: t.join() ``` 运行上述代码会创建3个线程,并且每个线程会在循环内打印输出线程的名称和循环的次数。示例输出可能如下所示: ``` This is a thread: Thread-1 Loop: 0 This is a thread: Thread-2 Loop: 0 This is a thread: Thread-3 Loop: 0 This is a thread: Thread-3 Loop: 1 This is a thread: Thread-2 Loop: 1 This is a thread: Thread-1 Loop: 1 This is a thread: Thread-2 Loop: 2 This is a thread: Thread-3 Loop: 2 This is a thread: Thread-1 Loop: 2 This is a thread: Thread-2 Loop: 3 This is a thread: Thread-3 Loop: 3 This is a thread: Thread-1 Loop: 3 This is a thread: Thread-2 Loop: 4 This is a thread: Thread-3 Loop: 4 This is a thread: Thread-1 Loop: 4 ``` 每个线程会按照不同的顺序交替执行循环,打印输出内容。 ######[AI写代码神器 | 767点数解答 | 2024-05-24 10:56:07]
- 2025 暑假苍溪 - 广安 - 重庆红色研学:中小学生传承红色基因之旅 (字节豆包 | 1244点数解答 | 2025-06-19 16:32:34)251
- Python 运行报错:urllib3 网络连接创建失败,原因及排查建议(字节豆包 | 161点数解答 | 2024-10-31 00:39:36)487
- Java实现链表反转:迭代与递归双解法详解及开发实战指南(DeepSeek | 1409点数解答 | 2026-03-15 15:09:29)52
- ClickHouse 表只读模式错误:原因、解决方案及代码检查示例(DeepSeek | 404点数解答 | 2025-02-11 14:14:17)229
- Java 创建 HTTP POST 请求实现文件上传:代码示例与注意要点 (字节豆包 | 300点数解答 | 2024-12-06 16:07:20)352
- Python 实战:学生信息列表转字典、遍历、深拷贝及数据修改全流程(GPT | 422点数解答 | 2024-10-29 15:43:54)439
- Python实战:学生成绩列表转字典,深拷贝与数据修改操作全解析(字节豆包 | 254点数解答 | 2024-10-29 16:01:39)434
- 易语言实现高并发 HTTP 操作:多线程、线程池与异步操作实战(字节豆包 | 849点数解答 | 2025-06-03 23:17:33)282
- 易语言多线程启动:如何传递并处理文本数组及注意要点(字节豆包 | 610点数解答 | 2025-08-04 18:05:23)196
- 探寻数组中最长摆动子序列长度:思路剖析与代码优化(GPT | 758点数解答 | 2024-12-23 23:18:29)285
- 独家剖析:求解数组最长摆动子序列长度的代码实现与改进建议(GPT | 350点数解答 | 2024-12-23 23:20:54)282
- C++实现读取数字并输出最小值的代码及解释(字节豆包 | 113点数解答 | 2026-03-20 19:32:56)24