python多线程示例1(工作太忙,仅仅作为记录)

 1 import threading
 2 
 3 # 多线程本质上是在一个 Python 程序里做的一个资源再分配,把几段代码的运行顺序进行先后调整达到 CPU 资源利用的最大化。
 4 
 5 # 直接继承线程类,然后覆盖继承类函数的方法
 6 class ThreadChild(threading.Thread):
 7     # 初始化 init: 通常继承线程类会扩写父类的初始化,来传递参数等。
 8     def __init__(self, times, name, ret_dic):
 9         # 扩写父类的初始化,首先调用父类的初始化
10         threading.Thread.__init__(self)
11         self.times = times
12         self.name = name
13         self.ret_dic = ret_dic
14         return
15 
16     # 运行 run: 这是一个必须要覆盖的函数。启动线程调用的 start() 函数就是运行这个函数,这里是需要运行的核心代码。
17     def run(self):
18         # 覆盖重写函数 run
19         for i in range(self.times):
20             print(self.name + ' run: ' + str(i))
21         self.ret_dic[self.name] = self.name + " finished with " + str(self.times) + " times printed"
22         return
23 
24 
25 if __name__ == '__main__':
26 
27     thread_pool = []
28     ret_dic = {}
29     th_1 = ThreadChild(times=3, name='th_1', ret_dic=ret_dic)
30     th_2 = ThreadChild(times=5, name='th_2', ret_dic=ret_dic)
31     thread_pool.append(th_1)
32     thread_pool.append(th_2)
33 
34     # 非阻塞 start()
35     for th in thread_pool:
36         th.start()
37     # 阻塞 join()
38     for th in thread_pool:
39         th.join()
40 
41     print(ret_dic)

 

posted @ 2021-09-06 15:45  土博姜山山  阅读(83)  评论(0编辑  收藏  举报