启动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.
时间: 2023-10-01 20:09:24 浏览: 81
好的,我可以为您提供一个Python的示例代码,如下所示:
```python
import threading
class PrintThread(threading.Thread):
def __init__(self, start_num, end_num, step, lock):
super().__init__()
self.start_num = start_num
self.end_num = end_num
self.step = step
self.lock = lock
def run(self):
for i in range(self.start_num, self.end_num+1, self.step):
with self.lock:
print(i, end=" ")
print()
if __name__ == "__main__":
lock = threading.Lock()
thread1 = PrintThread(1, 5, 1, lock)
thread2 = PrintThread(6, 10, 1, lock)
thread3 = PrintThread(11, 15, 1, lock)
thread1.start()
thread2.start()
thread3.start()
thread1.join()
thread2.join()
thread3.join()
for i in range(16, 76, 15):
with lock:
for j in range(i, i+5):
print(j, end=" ")
print()
```
这里我们定义了一个PrintThread类,每个线程通过传入的参数来打印指定的数字范围。同时,我们使用了一个Lock来保证线程安全,避免多个线程同时打印同一个数字。接下来我们启动三个线程来打印1-15的数字,然后再通过循环打印16-75的数字。
阅读全文