python多线程有几种实现方法
生活随笔
收集整理的這篇文章主要介紹了
python多线程有几种实现方法
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
python多線程有幾種實現(xiàn)方法,都是什么?
??????? 一般來說,使用線程有兩種模式:
??????? A 創(chuàng)建線程要執(zhí)行的函數(shù),把這個函數(shù)傳遞進Thread對象里,讓它來執(zhí)行;
??????? B 繼承Thread類,創(chuàng)建一個新的class,將要執(zhí)行的代碼 寫到run函數(shù)里面。
第一種 創(chuàng)建函數(shù)并且傳入Thread 對象中
import threading,timefrom time import sleep, ctimedef now() :return str( time.strftime( '%Y-%m-%d %H:%M:%S' , time.localtime() ) )def test(nloop, nsec):print 'start loop', nloop, 'at:', now()sleep(nsec)print 'loop', nloop, 'done at:', now()def main():print 'starting at:',now()threadpool=[]for i in xrange(10):th = threading.Thread(target= test,args= (i,2))threadpool.append(th)for th in threadpool:th.start()for th in threadpool :threading.Thread.join( th )print 'all Done at:', now()if __name__ == '__main__':main()
第二種是創(chuàng)建一個新的class,將要執(zhí)行的代碼 寫到run函數(shù)里面。
import threading ,timefrom time import sleep, ctimedef now() :return str( time.strftime( '%Y-%m-%d %H:%M:%S' , time.localtime() ) )class myThread (threading.Thread) :"""docstring for myThread"""def __init__(self, nloop, nsec) :super(myThread, self).__init__()self.nloop = nloopself.nsec = nsecdef run(self):print 'start loop', self.nloop, 'at:', ctime()sleep(self.nsec)print 'loop', self.nloop, 'done at:', ctime()def main():thpool=[]print 'starting at:',now()for i in xrange(10):thpool.append(myThread(i,2))for th in thpool:th.start()for th in thpool:th.join()print 'all Done at:', now()if __name__ == '__main__':main()
總結(jié)
以上是生活随笔為你收集整理的python多线程有几种实现方法的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 人工智能NLP自然语言之基础篇文本分类p
- 下一篇: NFC数据串口传输模块(NFC2COM)