以下是使用继承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 ``` 每个线程会按照不同的顺序交替执行循环,打印输出内容。 [2024-05-24 10:56:07 | AI写代码神器 | 767点数解答]