python继承threading.Thread实现有返回值的子类实例
作者:我不喜欢这个世界 时间:2023-06-07 19:01:15
继承与threading.Thread实现有返回值的子类MyThread,废话不多说,大家直接看代码
import threading
class MyThread(threading.Thread):
def __init__(self,func,args=()):
super(MyThread,self).__init__()
self.func = func
self.args = args
def run(self):
self.res = self.func(*self.args)
def getResult(self):
try:
return self.res
except Exception:
return None
补充知识:python3多线程自定义threading子类
解决问题
1、python3多线程自定义threading.Thread的子类;
2、多线程并行,获取多线程运行结果
代码实例
import threading
from time import sleep
exitFlag = True
def pp1(*args):
i = 1
while(exitFlag):
print('\r'+' '*20,end='')
print('\r线程1运行中'+'.'*(i%7),end='')
sleep(0.5)
i = (i>=6 and 1 or i+1) #if i>=6则i=1,否则i=i+1
print('线程1结束')
def pp2(x,y):
sleep(3)
print('\n线程2结束')
return x + y
class MyThread(threading.Thread): #MyThread类继承threading.Thread类
def __init__(self,func,args1=None,args2=None):
threading.Thread.__init__(self)
self.func = func
self.args1 = args1
self.args2 = args2
def run(self): #t.start()语句调用run方法
self.result = self.func(self.args1,self.args2)
def getResult(self): #getResult方法可获得func函数return的结果
threading.Thread.join(self)
return self.result
t1 = MyThread(pp1) #初始化t1
t2 = MyThread(pp2,2,3) #初始化t1
t1.start() #启动线程t1
t2.start() #启动线程t2
t2.join() #判断线程t2运行结束
exitFlag = False #线程2运行结束后,线程1才能结束
t1.join() #判断线程t1运行结束,线程t1结束后,主线程才能往下运行
print('线程2返回结果: ',t2.getResult())
print('主线程结束')
来源:https://blog.csdn.net/m0_38124502/article/details/86477591
标签:python,threading,Thread,返回值,子类
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
SQL Server 数据库索引其索引的小技巧
2024-01-21 03:13:40
Python 并行化执行详细解析
2021-09-23 22:20:52
![](https://img.aspxhome.com/file/2023/0/70680_0s.png)
pandas之分组groupby()的使用整理与总结
2022-04-23 17:24:42
![](https://img.aspxhome.com/file/2023/3/108033_0s.png)
windows 下python+numpy安装实用教程
2022-06-26 09:52:26
Perl 哈希Hash用法之入门教程
2023-11-06 22:57:17
JavaScript使用focus()设置焦点失败的解决方法
2024-05-02 16:28:15
SQL Server查询速度慢原因及优化方法
2008-12-03 15:19:00
Python中规范定义命名空间的一些建议
2022-05-16 17:05:24
Python项目管理Git常用命令详图讲解
2021-01-24 13:41:38
![](https://img.aspxhome.com/file/2023/1/64311_0s.png)
python+opencv实现堆叠图片
2023-07-19 21:22:45
![](https://img.aspxhome.com/file/2023/8/105588_0s.jpg)
python3 lambda表达式详解
2021-03-01 20:28:20
JS实现将Asp.Net的DateTime Json类型转换为标准时间的方法
2024-04-18 10:03:09
Python编辑器Pycharm安装配置超详细教程
2023-03-25 14:55:15
![](https://img.aspxhome.com/file/2023/2/101062_0s.jpg)
java连接mysql数据库详细步骤解析
2024-01-19 15:55:25
![](https://img.aspxhome.com/file/2023/8/89498_0s.jpg)
详解.NET数据库连接池
2024-01-20 16:05:59
![](https://img.aspxhome.com/file/2023/0/87040_0s.png)
Python入门教程(五)Python变量的用法
2021-04-05 11:17:35
![](https://img.aspxhome.com/file/2023/3/113123_0s.png)
Sql Server 2012 转换函数的比较(Cast、Convert和Parse)
2012-08-21 10:21:40
Python OpenCV中cv2.minAreaRect实例解析
2022-09-02 19:36:58
![](https://img.aspxhome.com/file/2023/7/131197_0s.png)
Golang 错误捕获Panic与Recover的使用
2024-02-07 20:15:42
还原大备份mysql文件失败的解决方法分享
2024-01-26 17:42:04