Python 的多線程有兩種實(shí)現(xiàn)方法:
函數(shù),線程類
1.函數(shù)
調(diào)用 thread 模塊中的 start_new_thread() 函數(shù)來創(chuàng)建線程,以線程函數(shù)的形式告訴線程該做什么
代碼如下:
# -*- coding: utf-8 -*-
import thread
def f(name):
#定義線程函數(shù)
print "this is " + name
if __name__ == '__main__':
thread.start_new_thread(f, ("thread1",))
#用start_new_thread()調(diào)用線程函數(shù)和其他參數(shù)
while 1:
pass
不過這種方法暫時沒能找到其他輔助方法,連主線程等待都要用 while 1 這種方法解決。
2.線程類
調(diào)用 threading 模塊,創(chuàng)建 threading.Thread 的子類來得到自定義線程類。
代碼如下:
# -*- coding: utf-8 -*-
import threading
class Th(threading.Thread):
def __init__(self, name):
threading.Thread.__init__(self)
self.t_name = name
#調(diào)用父類構(gòu)造函數(shù)
def run(self):
#重寫run()函數(shù),線程默認(rèn)從此函數(shù)開始執(zhí)行
print "This is " + self.t_name
if __name__ == '__main__':
thread1 = Th("Thread_1")
thread1.start()
#start()函數(shù)啟動線程,自動執(zhí)行run()函數(shù)
threading.Thread 類的可繼承函數(shù):
getName() 獲得線程對象名稱
setName() 設(shè)置線程對象名稱
join() 等待調(diào)用的線程結(jié)束后再運(yùn)行之后的命令
setDaemon(bool) 阻塞模式, True: 父線程不等待子線程結(jié)束, False 等待,默認(rèn)為 False
isDaemon() 判斷子線程是否和父線程一起結(jié)束,即 setDaemon() 設(shè)置的值
isAlive() 判斷線程是否在運(yùn)行
實(shí)例
代碼如下:
import threading
import time
class Th(threading.Thread):
def __init__(self, thread_name):
threading.Thread.__init__(self)
self.setName(thread_name)
def run(self):
print "This is thread " + self.getName()
for i in range(5):
time.sleep(1)
print str(i)
print self.getName() + "is over"
join() 阻塞等待
代碼如下:
if __name__ == '__main__':
thread1 = Th("T1 ")
thread1.start()
#thread1.join()
print "main thread is over"
不帶 thread1.join() ,得到如下結(jié)果:
代碼如下:
This is thread T1
main thread is over
0
1
2
T1 is over
不等待 thread1 完成,執(zhí)行之后語句。
加了 thread1.join() ,得到如下結(jié)果:
新聞熱點(diǎn)
疑難解答
圖片精選