首页 > 编程语言 > 详细

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

时间:2021-09-06 21:16:08      阅读:31      评论:0      收藏:0      [点我收藏+]
 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)

 

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

原文:https://www.cnblogs.com/jeshy/p/15234052.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!