python繼承threading.Thread實現(xiàn)有返回值的子類實例
更新時間:2020年05月02日 10:04:27 作者:我不喜歡這個世界
這篇文章主要介紹了python繼承threading.Thread實現(xiàn)有返回值的子類實例,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧
繼承與threading.Thread實現(xiàn)有返回值的子類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、多線程并行,獲取多線程運行結(jié)果
代碼實例
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結(jié)束')
def pp2(x,y):
sleep(3)
print('\n線程2結(jié)束')
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()語句調(diào)用run方法
self.result = self.func(self.args1,self.args2)
def getResult(self): #getResult方法可獲得func函數(shù)return的結(jié)果
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運行結(jié)束
exitFlag = False #線程2運行結(jié)束后,線程1才能結(jié)束
t1.join() #判斷線程t1運行結(jié)束,線程t1結(jié)束后,主線程才能往下運行
print('線程2返回結(jié)果: ',t2.getResult())
print('主線程結(jié)束')
以上這篇python繼承threading.Thread實現(xiàn)有返回值的子類實例就是小編分享給大家的全部內(nèi)容了,希望能給大家一個參考,也希望大家多多支持腳本之家。
您可能感興趣的文章:
- Python中threading庫實現(xiàn)線程鎖與釋放鎖
- Python多線程編程之threading模塊詳解
- Python 多線程之threading 模塊的使用
- python中threading和queue庫實現(xiàn)多線程編程
- Python threading模塊condition原理及運行流程詳解
- Python多線程threading創(chuàng)建及使用方法解析
- Python3 socket即時通訊腳本實現(xiàn)代碼實例(threading多線程)
- Python中使用threading.Event協(xié)調(diào)線程的運行詳解
- 淺談Python中threading join和setDaemon用法及區(qū)別說明
- python中threading開啟關(guān)閉線程操作
- python threading模塊的使用指南
相關(guān)文章
python 統(tǒng)計列表中不同元素的數(shù)量方法
今天小編就為大家分享一篇python 統(tǒng)計列表中不同元素的數(shù)量方法,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2018-06-06
Python中Matplotlib圖像添加標簽的方法實現(xiàn)
本文主要介紹了Python中Matplotlib圖像添加標簽的方法實現(xiàn),文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2023-04-04
TensorFlow基于MNIST數(shù)據(jù)集實現(xiàn)車牌識別(初步演示版)
這篇文章主要介紹了TensorFlow基于MNIST數(shù)據(jù)集實現(xiàn)車牌識別(初步演示版),文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2019-08-08

