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

#coding=utf-8 import threading,time def test(): t = threading.currentThread() # 獲取當前子線程對象 print t.getName() # 打印當前子線程名字 i=0 while i<10: print i time.sleep(1) i=i+1 m=threading.Thread(target=test,args=(),name='循環(huán)子線程') #初始化一個子線程對象,target是執(zhí)行的目標函數(shù),args是目標函數(shù)的參數(shù),name是子線程的名字 m.start() t=threading.currentThread() #獲取當前線程對象,這里其實是主線程 print t.getName() #打印當前線程名字,其實是主線程名字
2、通過基礎thread類來創(chuàng)建,需要創(chuàng)建一個自定義線程
import threading,time
class myThread (threading.Thread): #創(chuàng)建一個自定義線程類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)建線程的兩種方式,希望能對大家有所幫助。更多Python學習指路:創(chuàng)新互聯(lián)python教程
本文教程操作環(huán)境:windows7系統(tǒng)、Python 3.9.1,DELL G3電腦。
網(wǎng)站題目:創(chuàng)新互聯(lián)Python教程:threading在python中創(chuàng)建線程的兩種方式
網(wǎng)站URL:http://m.fisionsoft.com.cn/article/copecgd.html


咨詢
建站咨詢
