Python多线程Thread——生产者消费者模型-CSDN博客
import random
import threading
import time
# 主线程
class MainThread(threading.Thread):
def __init__(self, name, num=0, target=10):
super(MainThread, self).__init__()
self.name = name # 主线程名字
self.num = num # 子线程数量
self.target = target # 停止计数
self.subThreadList = self.genSubThreadList() # 子线程列表
self.n = 0 # 计数器
def genSubThreadList(self): # 构建子线程列表
temp_list = []
if self.num:
for i in range(self.num + 1):
temp_list.append(SubThread(self.name, str(i), self.target)) # 构建子线程
return temp_list
def run(self):
for i in self.subThreadList: # 运行子线程
i.start()
# i.join()
while True:
time.sleep(1)
self.n += 1
print(f"{self.name}正在运行第{self.n}次")
if self.n == self.target:
print(f"{self.name}运行完毕")
break
# 子线程
class SubThread(threading.Thread):
def __init__(self, fName, name, target=10):
super(SubThread, self).__init__()
self.fName = fName # 父线程名字
self.name = name # 子线程名字
self.target = target
self.n = 0
self.num = random.randint(1, 4) # 随机时间s
def run(self):
time_cost = 0 # 累计时间
while True:
time.sleep(self.num)
self.n += 1
print(f"{self.fName}的子线程{self.name}正在运行第{self.n}次")
time_cost += self.num
if self.n == self.target:
print(f"{self.fName}的子线程{self.name}运行结束,耗时{time_cost}s")
break
if __name__ == '__main__':
mt1 = MainThread("一号线程", 3)
mt2 = MainThread("九号线程", 2)
mt1.start()
mt2.start()