Python多线程thread与子线程

2023-12-13 06:55:06

Python多线程Thread——生产者消费者模型-CSDN博客

python队列与多线程——生产者消费者模型-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()

文章来源:https://blog.csdn.net/weixin_71370467/article/details/134950195
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。