溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶服務(wù)條款》

Python線程的編程方式

發(fā)布時(shí)間:2021-08-25 15:09:00 來(lái)源:億速云 閱讀:103 作者:chen 欄目:編程語(yǔ)言

這篇文章主要講解了“Python線程的編程方式”,文中的講解內(nèi)容簡(jiǎn)單清晰,易于學(xué)習(xí)與理解,下面請(qǐng)大家跟著小編的思路慢慢深入,一起來(lái)研究和學(xué)習(xí)“Python線程的編程方式”吧!

1、調(diào)用thread模塊中的start_new_thread()函數(shù)來(lái)產(chǎn)生新的線程,請(qǐng)看代碼:

# thread_example.py   import time   import thread   def timer(no,interval): #自己寫(xiě)的線程函數(shù)         while True:               print 'Thread :(%d) Time:%s'%(no,time.ctime()) time.sleep(interval)     def test(): #使用thread.start_new_thread()來(lái)產(chǎn)生2個(gè)新的線程           thread.start_new_thread(timer,(1,1))        thread.start_new_thread(timer,(2,3))     if __name__=='__main__':         test()

這個(gè)是thread.start_new_thread(function,args[,kwargs])函數(shù)原型,其中function參數(shù)是你將要調(diào)用的線程函數(shù);args是講傳遞給你的線程函數(shù)的參數(shù),他必須是個(gè)tuple類(lèi)型;而kwargs是可選的參數(shù),線程的結(jié)束一般依靠線程函數(shù)的自然結(jié)束;也可以在線程函數(shù)中調(diào)用thread.exit(),他拋出SystemExit exception,達(dá)到退出線程的目的。

2、通過(guò)調(diào)用threading模塊繼承threading.Thread類(lèi)來(lái)包裝一個(gè)線程對(duì)象。請(qǐng)看代碼:

import threading    import time    class timer(threading.Thread):     #我的timer類(lèi)繼承自threading.Thread類(lèi)         def __init__(self,no,interval):             #在我重寫(xiě)__init__方法的時(shí)候要記得調(diào)用基類(lèi)的__init__方法             threading.Thread.__init__(self)                  self.no=no             self.interval=interval                      def run(self):  #重寫(xiě)run()方法,把自己的線程函數(shù)的代碼放到這里             while True:                 print 'Thread Object (%d), Time:%s'%(self.no,time.ctime())                 time.sleep(self.interval)                      def test():          threadone=timer(1,1)    #產(chǎn)生2個(gè)線程對(duì)象          threadtwo=timer(2,3)          threadone.start()   #通過(guò)調(diào)用線程對(duì)象的.start()方法來(lái)激活線程          threadtwo.start()              if __name__=='__main__':          test()

其實(shí)thread和threading的模塊中還包含了其他的很多關(guān)于多線程編程的東西,例如鎖、定時(shí)器、獲得激活線程列表等等,請(qǐng)大家仔細(xì)參考Python線程編程的文檔!

感謝各位的閱讀,以上就是“Python線程的編程方式”的內(nèi)容了,經(jīng)過(guò)本文的學(xué)習(xí)后,相信大家對(duì)Python線程的編程方式這一問(wèn)題有了更深刻的體會(huì),具體使用情況還需要大家實(shí)踐驗(yàn)證。這里是億速云,小編將為大家推送更多相關(guān)知識(shí)點(diǎn)的文章,歡迎關(guān)注!

向AI問(wèn)一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI