您好,登錄后才能下訂單哦!
本篇內(nèi)容介紹了“Python線程的常用屬性以及直接繼承子類threading.Thread的過程”的有關(guān)知識,在實際案例的操作過程中,不少人都會遇到這樣的困境,接下來就讓小編帶領(lǐng)大家學(xué)習(xí)一下如何處理這些情況吧!希望大家仔細閱讀,能夠?qū)W有所成!
一、線程常用屬性
1.threading.currentThread:返回當(dāng)前線程變量
2.threading.enumerate:返回一個包含正在運行的線程的list,正在運行的線程指的是線程啟動后,結(jié)束前的狀態(tài)
3.threading.activeCount:返回正在運行的線程數(shù)量,效果跟len(threading.enumer)一樣
4.thr.setName:給線程設(shè)置名字
5.thr.getName:得到線程的名字。
舉例:
mport _thread as thread import time def loop1(in1): print("Start loop 1 at:", time.ctime()) print("我是參數(shù)", in1) time.sleep(4) print("End loop 1 at:", time.ctime()) def loop2(in1, in2): print("Start loop 2 at:", time.ctime()) print("我是參數(shù)", in1, "和參數(shù) ", in2) time.sleep(4) print("End loop 2 at:", time.ctime()) import threading def main1(): print("Starting at:", time.ctime()) t1 = threading.Thread(target = loop1, args = ('', )) t1.setName("THR_1")# 給線程重命名 t1.start() t2 = threading.Thread(target = loop2, args = ('', '')) t2.setName("THR_2") t2.setDaemon(True)# 主線程運行完了就完了, 不用等線程2 t2.start() time.sleep(3)# 三秒后兩個子線程仍然在運行著, 因為他們里面有一個四秒在停著 for thr in threading.enumerate(): #返回的是正在運行的子線程的列表 print("正在運行的子線程名為:{0}".format(thr.getName()))# 讀取了該線程的名字 print("正在運行的子線程數(shù)量為:{0}".format(threading.activeCount()))# 打印出了線程的數(shù)量, 包括主線程和兩個子線程一共3個線程 t1.join()# 等線程1運行完了再接著向下運行 print("ALL done at :", time.ctime()) if __name__ == "__main__": main1()
二、直接繼承子類threading.Thread
1.直接繼承Thread;重寫run函數(shù)
2.例子:
class MyThread(threading.Thread): #定義一個Thread的子類 def __init__(self, args): #重寫__init__函數(shù), 其中參數(shù)為self和新引入的參數(shù) super(MyThread, self).__init__()# 固定格式, 繼承父類的__init__函數(shù) self.args = args def run(self): time.sleep(1) print("The args for this class is {0}".format(self.args)) for i in range(5): t = MyThread(i) t.start() t.join()
“Python線程的常用屬性以及直接繼承子類threading.Thread的過程”的內(nèi)容就介紹到這里了,感謝大家的閱讀。如果想了解更多行業(yè)相關(guān)的知識可以關(guān)注億速云網(wǎng)站,小編將為大家輸出更多高質(zhì)量的實用文章!
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。