創(chuàng)新互聯(lián)www.cdcxhl.cn八線動(dòng)態(tài)BGP香港云服務(wù)器提供商,新人活動(dòng)買多久送多久,劃算不套路!
為德州等地區(qū)用戶提供了全套網(wǎng)頁(yè)設(shè)計(jì)制作服務(wù),及德州網(wǎng)站建設(shè)行業(yè)解決方案。主營(yíng)業(yè)務(wù)為成都網(wǎng)站設(shè)計(jì)、成都網(wǎng)站建設(shè)、德州網(wǎng)站設(shè)計(jì),以傳統(tǒng)方式定制建設(shè)網(wǎng)站,并提供域名空間備案等一條龍服務(wù),秉承以專業(yè)、用心的態(tài)度為用戶提供真誠(chéng)的服務(wù)。我們深信只要達(dá)到每一位用戶的要求,就會(huì)得到認(rèn)可,從而選擇與我們長(zhǎng)期合作。這樣,我們也可以走得更遠(yuǎn)!小編給大家分享一下Python中生成線程的方法有哪些,希望大家閱讀完這篇文章后大所收獲,下面讓我們一起去探討吧!
Python中有兩個(gè)線程模塊,分別是thread和threading,threading是thread的升級(jí)版。threading的功能更強(qiáng)大。
創(chuàng)建線程有3種方法:
1、thread模塊的start_new_thread函數(shù)
2、繼承自threading.Thread模塊
3、用theading.Thread直接返回一個(gè)thread對(duì)象,然后運(yùn)行它的start方法
方法一、thread模塊的start_new_thread函數(shù)
其函數(shù)原型:
start_new_thread(function,atgs[,kwargs])
其參數(shù)含義如下:
function: 在線程中執(zhí)行的函數(shù)名 args:元組形式的參數(shù)列表。 kwargs: 可選參數(shù),以字典的形式指定參數(shù)(即對(duì)一些參數(shù)進(jìn)行指定初始化)
代碼
import thread def hello(id = 0, interval = 2): for i in filter(lambda x: x % interval == 0, range(10)): print "Thread id : %d, time is %d\n" % (id, i) if __name__ == "__main__": #thread.start_new_thread(hello, (1,2)) 這種調(diào)用形式也是可用的 #thread.start_new_thread(hello, (2,4)) thread.start_new_thread(hello, (), {"id": 1}) thread.start_new_thread(hello, (), {"id": 2})
方法二:繼承自threading.Thread模塊
注意:必須重寫run函數(shù),而且想要運(yùn)行應(yīng)該調(diào)用start方法
import threading class MyThread(threading.Thread): def __init__(self, id, interval): threading.Thread.__init__(self) self.id = id self.interval = interval def run(self): for x in filter(lambda x: x % self.interval == 0, range(10)): print "Thread id : %d time is %d \n" % (self.id, x) if __name__ == "__main__": t1 = MyThread(1, 2) t2 = MyThread(2, 4) t1.start() t2.start() t1.join() t2.join()
方法三:用theading.Thread直接返回一個(gè)thread對(duì)象,然后運(yùn)行它的start方法
import threading def hello(id, times): for i in range(times): print "hello %s time is %d\n" % (id , i) if __name__ == "__main__": t = threading.Thread(target=hello, args=("hawk", 5)) t.start()
看完了這篇文章,相信你對(duì)Python中生成線程的方法有哪些有了一定的了解,想了解更多相關(guān)知識(shí),歡迎關(guān)注創(chuàng)新互聯(lián)-成都網(wǎng)站建設(shè)公司行業(yè)資訊頻道,感謝各位的閱讀!
當(dāng)前題目:Python中生成線程的方法有哪些-創(chuàng)新互聯(lián)
本文網(wǎng)址:http://www.rwnh.cn/article12/copedc.html
成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供做網(wǎng)站、網(wǎng)站策劃、建站公司、面包屑導(dǎo)航、微信小程序、品牌網(wǎng)站制作
聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請(qǐng)盡快告知,我們將會(huì)在第一時(shí)間刪除。文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如需處理請(qǐng)聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時(shí)需注明來(lái)源: 創(chuàng)新互聯(lián)
猜你還喜歡下面的內(nèi)容