3. 启动3个线程打印递增的数字,控制线程 1打印1,2,3,4,5(每行都打印线程名和一个数字),线程2打印6,7,8,9,10,线程3打印11,12,13, 14, 15:接下来再由线程1打印16,17, 18,19, 20, ••依次类推,直到打印75。
时间: 2024-03-22 16:37:26 浏览: 50
好的,这是一个多线程的问题,我可以帮你解答。下面是一个可能的解决方案:
```python
import threading
class NumberPrinter:
def __init__(self, start_num, end_num, thread_name):
self.start_num = start_num
self.end_num = end_num
self.thread_name = thread_name
def print_numbers(self):
for i in range(self.start_num, self.end_num + 1):
print(self.thread_name, i)
# 创建3个NumberPrinter对象,分别打印1-5,6-10,11-15
printer1 = NumberPrinter(1, 5, "Thread-1")
printer2 = NumberPrinter(6, 10, "Thread-2")
printer3 = NumberPrinter(11, 15, "Thread-3")
# 创建3个线程,分别执行3个NumberPrinter的print_numbers方法
t1 = threading.Thread(target=printer1.print_numbers)
t2 = threading.Thread(target=printer2.print_numbers)
t3 = threading.Thread(target=printer3.print_numbers)
# 启动3个线程
t1.start()
t2.start()
t3.start()
# 等待3个线程执行完毕
t1.join()
t2.join()
t3.join()
# 根据题目要求,依次打印16-20, 21-25, ..., 71-75
for i in range(16, 76, 5):
printer1 = NumberPrinter(i, i+4, "Thread-1")
t1 = threading.Thread(target=printer1.print_numbers)
t1.start()
t1.join()
```
这个代码中,我们首先创建了一个`NumberPrinter`类,它包含了打印数字的起始和终止值,以及线程的名字。`print_numbers`方法用来打印数字。然后我们创建了3个`NumberPrinter`对象,分别打印1-5,6-10,11-15,然后创建3个线程分别执行它们的`print_numbers`方法。最后,根据题目要求,依次打印16-20, 21-25, ..., 71-75。
阅读全文