启动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-05-15 12:14:33 浏览: 78
以下是一个示例代码,使用Python的多线程来实现:
```python
import threading
class PrintThread(threading.Thread):
def __init__(self, start_num, end_num):
super(PrintThread, self).__init__()
self.start_num = start_num
self.end_num = end_num
def run(self):
for i in range(self.start_num, self.end_num+1):
print("{}: {}".format(self.getName(), i))
if i % 5 == 0:
# 当打印到5的倍数时,通知下一个线程开始打印
event.set()
event.clear()
if __name__ == "__main__":
event = threading.Event()
thread1 = PrintThread(1, 5)
thread2 = PrintThread(6, 10)
thread3 = PrintThread(11, 15)
# 在循环打印时,通过event.wait()阻塞当前线程,等待上一个线程通知再继续打印
event.set()
while True:
event.wait()
if thread1.is_alive():
thread1.join(0.1)
if thread2.is_alive():
thread2.join(0.1)
if thread3.is_alive():
thread3.join(0.1)
if not thread1.is_alive() and not thread2.is_alive() and not thread3.is_alive():
break
if not thread1.is_alive():
thread1 = PrintThread(thread1.end_num+1, thread1.end_num+5)
thread1.start()
elif not thread2.is_alive():
thread2 = PrintThread(thread2.end_num+1, thread2.end_num+5)
thread2.start()
elif not thread3.is_alive():
thread3 = PrintThread(thread3.end_num+1, thread3.end_num+5)
thread3.start()
```
这个代码会启动三个线程,分别打印1-5,6-10,11-15。然后在循环中等待每个线程打印完毕后,判断哪个线程已经结束,然后启动一个新的线程打印下一个数字。每个线程打印到5的倍数时,会通过event来通知下一个线程开始打印。直到打印完75后,程序结束。
阅读全文