這篇文章主要講解了“Python線程的編程方式”,文中的講解內容簡單清晰,易于學習與理解,下面請大家跟著小編的思路慢慢深入,一起來研究和學習“Python線程的編程方式”吧!
1、調用thread模塊中的start_new_thread()函數來產生新的線程,請看代碼:
# thread_example.py import time import thread def timer(no,interval): #自己寫的線程函數 while True: print 'Thread :(%d) Time:%s'%(no,time.ctime()) time.sleep(interval) def test(): #使用thread.start_new_thread()來產生2個新的線程 thread.start_new_thread(timer,(1,1)) thread.start_new_thread(timer,(2,3)) if __name__=='__main__': test()
這個是thread.start_new_thread(function,args[,kwargs])函數原型,其中function參數是你將要調用的線程函數;args是講傳遞給你的線程函數的參數,他必須是個tuple類型;而kwargs是可選的參數,線程的結束一般依靠線程函數的自然結束;也可以在線程函數中調用thread.exit(),他拋出SystemExit exception,達到退出線程的目的。
2、通過調用threading模塊繼承threading.Thread類來包裝一個線程對象。請看代碼:
import threading import time class timer(threading.Thread): #我的timer類繼承自threading.Thread類 def __init__(self,no,interval): #在我重寫__init__方法的時候要記得調用基類的__init__方法 threading.Thread.__init__(self) self.no=no self.interval=interval def run(self): #重寫run()方法,把自己的線程函數的代碼放到這里 while True: print 'Thread Object (%d), Time:%s'%(self.no,time.ctime()) time.sleep(self.interval) def test(): threadone=timer(1,1) #產生2個線程對象 threadtwo=timer(2,3) threadone.start() #通過調用線程對象的.start()方法來激活線程 threadtwo.start() if __name__=='__main__': test()
其實thread和threading的模塊中還包含了其他的很多關于多線程編程的東西,例如鎖、定時器、獲得激活線程列表等等,請大家仔細參考Python線程編程的文檔!
感謝各位的閱讀,以上就是“Python線程的編程方式”的內容了,經過本文的學習后,相信大家對Python線程的編程方式這一問題有了更深刻的體會,具體使用情況還需要大家實踐驗證。這里是億速云,小編將為大家推送更多相關知識點的文章,歡迎關注!
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。