新聞中心
這里有您想知道的互聯(lián)網(wǎng)營(yíng)銷解決方案
創(chuàng)新互聯(lián)Python教程:threading在python中創(chuàng)建線程的兩種方式
1、直接通過(guò)初始化thread對(duì)象創(chuàng)建:

#coding=utf-8 import threading,time def test(): t = threading.currentThread() # 獲取當(dāng)前子線程對(duì)象 print t.getName() # 打印當(dāng)前子線程名字 i=0 while i<10: print i time.sleep(1) i=i+1 m=threading.Thread(target=test,args=(),name='循環(huán)子線程') #初始化一個(gè)子線程對(duì)象,target是執(zhí)行的目標(biāo)函數(shù),args是目標(biāo)函數(shù)的參數(shù),name是子線程的名字 m.start() t=threading.currentThread() #獲取當(dāng)前線程對(duì)象,這里其實(shí)是主線程 print t.getName() #打印當(dāng)前線程名字,其實(shí)是主線程名字
2、通過(guò)基礎(chǔ)thread類來(lái)創(chuàng)建,需要?jiǎng)?chuàng)建一個(gè)自定義線程
import threading,time
class myThread (threading.Thread): #創(chuàng)建一個(gè)自定義線程類mythread,繼承Thread
def __init__(self,name):
"""
重新init方法
:param name: 線程名
"""
super(myThread, self).__init__(name=name)
# self.lock=lock
print '線程名'+name
def run(self):
"""
重新run方法,這里面寫我們的邏輯
:return:
"""
i=0
while i<10:
print i
time.sleep(1)
i=i+1
if __name__=='__main__':
t=myThread('mythread')
t.start()以上就是threading在python中創(chuàng)建線程的兩種方式,希望能對(duì)大家有所幫助。更多Python學(xué)習(xí)指路:創(chuàng)新互聯(lián)python教程
本文教程操作環(huán)境:windows7系統(tǒng)、Python 3.9.1,DELL G3電腦。
分享題目:創(chuàng)新互聯(lián)Python教程:threading在python中創(chuàng)建線程的兩種方式
文章地址:http://m.5511xx.com/article/copecgd.html


咨詢
建站咨詢
