Python 多線程的實例詳解
一)線程基礎
1、創(chuàng)建線程:
thread模塊提供了start_new_thread函數,用以創(chuàng)建線程。start_new_thread函數成功創(chuàng)建后還可以對其進行操作。
其函數原型:
start_new_thread(function,atgs[,kwargs])
其參數含義如下:
function: 在線程中執(zhí)行的函數名
args:元組形式的參數列表。
kwargs: 可選參數,以字典的形式指定參數
方法一:通過使用thread模塊中的函數創(chuàng)建新線程。
>>> import thread >>> def run(n): for i in range(n): print i >>> thread.start_new_thread(run,(4,)) #注意第二個參數一定要是元組的形式 53840 1 >>> 2 3 KeyboardInterrupt >>> thread.start_new_thread(run,(2,)) 17840 1 >>> thread.start_new_thread(run,(),{'n':4}) 39720 1 >>> 2 3 thread.start_new_thread(run,(),{'n':3}) 32480 1 >>> 2 方法二:通過繼承threading.Thread創(chuàng)建線程
>>> import threading >>> class mythread(threading.Thread): def __init__(self,num): threading.Thread.__init__(self) self.num = num def run(self): #重載run方法 print 'I am', self.num >>> t1 = mythread(1) >>> t2 = mythread(2) >>> t3 = mythread(3) >>> t1.start() #運行線程t1 I am >>> 1 t2.start() I am >>> 2 t3.start() I am >>> 3
方法三:使用threading.Thread直接在線程中運行函數。
import threading >>> def run(x,y): for i in range(x,y): print i >>> t1 = threading.Thread(target=run,args=(15,20)) #直接使用Thread附加函數args為函數參數 >>> t1.start() 15 >>> 16 17 18 19
二)Thread對象中的常用方法:
1、isAlive方法:
>>> import threading >>> import time >>> class mythread(threading.Thread): def __init__(self,id): threading.Thread.__init__(self) self.id = id def run(self): time.sleep(5) #休眠5秒 print self.id >>> t = mythread(1) >>> def func(): t.start() print t.isAlive() #打印線程狀態(tài) >>> func() True >>> 1
2、join方法:
原型:join([timeout])
timeout: 可選參數,線程運行的最長時間
import threading >>> import time #導入time模塊 >>> class Mythread(threading.Thread): def __init__(self,id): threading.Thread.__init__(self) self.id = id def run(self): x = 0 time.sleep(20) print self.id >>> def func(): t.start() for i in range(5): print i >>> t = Mythread(2) >>> func() 0 1 2 3 4 >>> 2 def func(): t.start() t.join() for i in range(5): print i >>> t = Mythread(3) >>> func() 3 0 1 2 3 4 >>>
新聞熱點
疑難解答