酷代码 AI
菜单
服务商
DeepSeek字节豆包讯飞星火
更多选项

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]

相关提问
本站限时免费提问中
实用工具查看更多
Linux在线手册 [开发类]
Jquery在线手册 [开发类]
今日油价 [生活类]
图片互转base64 [开发类]
时间转换器 [开发类]