启动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-09-30 16:05:00 浏览: 80
(多线程)leetcode1195. 交替打印字符串 最简单解法一个变量搞定
可以使用Python中的线程模块`threading`来实现多线程打印递增的数字。具体实现如下:
```python
import threading
class PrintThread(threading.Thread):
def __init__(self, start_num, end_num, step, lock):
threading.Thread.__init__(self)
self.start_num = start_num
self.end_num = end_num
self.step = step
self.lock = lock
def run(self):
num = self.start_num
while num <= self.end_num:
self.lock.acquire()
for i in range(self.step):
print(num, end=' ')
num += 1
print()
self.lock.release()
if __name__ == '__main__':
lock = threading.Lock()
t1 = PrintThread(1, 5, 5, lock)
t2 = PrintThread(6, 10, 5, lock)
t3 = PrintThread(11, 15, 5, lock)
t4 = PrintThread(16, 20, 5, lock)
t5 = PrintThread(21, 25, 5, lock)
t6 = PrintThread(26, 30, 5, lock)
t7 = PrintThread(31, 35, 5, lock)
t8 = PrintThread(36, 40, 5, lock)
t9 = PrintThread(41, 45, 5, lock)
t10 = PrintThread(46, 50, 5, lock)
t11 = PrintThread(51, 55, 5, lock)
t12 = PrintThread(56, 60, 5, lock)
t13 = PrintThread(61, 65, 5, lock)
t14 = PrintThread(66, 70, 5, lock)
t15 = PrintThread(71, 75, 5, lock)
t1.start()
t2.start()
t3.start()
t4.start()
t5.start()
t6.start()
t7.start()
t8.start()
t9.start()
t10.start()
t11.start()
t12.start()
t13.start()
t14.start()
t15.start()
t1.join()
t2.join()
t3.join()
t4.join()
t5.join()
t6.join()
t7.join()
t8.join()
t9.join()
t10.join()
t11.join()
t12.join()
t13.join()
t14.join()
t15.join()
```
该程序中创建了15个`PrintThread`线程对象,每个线程对象分别负责打印一段数字序列。`PrintThread`类继承自`threading.Thread`类,重写了`run()`方法,实现了打印数字的逻辑。使用`threading.Lock()`类创建了一个互斥锁,确保线程间的输出不会交叉。最后使用`start()`方法启动线程,使用`join()`方法等待线程结束。
阅读全文