新聞中心
Python中有兩個(gè)線程模塊,分別是thread和threading,threading是thread的升級(jí)版。threading的功能更強(qiáng)大。

創(chuàng)新互聯(lián)是一家集網(wǎng)站建設(shè),綿陽(yáng)企業(yè)網(wǎng)站建設(shè),綿陽(yáng)品牌網(wǎng)站建設(shè),網(wǎng)站定制,綿陽(yáng)網(wǎng)站建設(shè)報(bào)價(jià),網(wǎng)絡(luò)營(yíng)銷(xiāo),網(wǎng)絡(luò)優(yōu)化,綿陽(yáng)網(wǎng)站推廣為一體的創(chuàng)新建站企業(yè),幫助傳統(tǒng)企業(yè)提升企業(yè)形象加強(qiáng)企業(yè)競(jìng)爭(zhēng)力??沙浞譂M足這一群體相比中小企業(yè)更為豐富、高端、多元的互聯(lián)網(wǎng)需求。同時(shí)我們時(shí)刻保持專業(yè)、時(shí)尚、前沿,時(shí)刻以成就客戶成長(zhǎng)自我,堅(jiān)持不斷學(xué)習(xí)、思考、沉淀、凈化自己,讓我們?yōu)楦嗟钠髽I(yè)打造出實(shí)用型網(wǎ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模塊
注意:必須重寫(xiě)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() 文章標(biāo)題:創(chuàng)新互聯(lián)Python教程:Python如何生成線程
文章出自:http://m.fisionsoft.com.cn/article/dhggddp.html


咨詢
建站咨詢
