在學習python 多線程程式設計的時候,一定會使用一個函數join,本章内容通過例子講述join 在多線程程式設計中有哪些作用。
本文使用兩段代碼示範其功能
代碼一
import threading, time
def now() :
return str( time.strftime( '%Y-%m-%d %H:%M:%S' , time.localtime() ) )
def func1():
print 'start func1: ' + now() + "\n"
time.sleep(3)
print 'stop func1: ' + now() + "\n"
def func2():
print 'start func2: ' + now() + "\n"
time.sleep(5)
print 'stop func2: ', now() + "\n"
thtsk = []
thread1 = threading.Thread(target = func1)
thread1.start()
thtsk.append(thread1)
thread2 = threading.Thread(target = func2)
thread2.start()
thtsk.append(thread2)
print 'start join: ' + now() + "\n"
for thd in thtsk:
thd.join()
print 'end join: ' + now() + "\n"
該樣例中使用了兩個線程thread1,thread2,分别執行func1,func2,
其中
func1 的動作是列印開始時間,sleep 3s,列印結束時間
func2 的動作是列印開始時間,sleep 5s,列印結束時間。
後面使用start() 方法同步開始執行兩個線程,然後開始循環調用兩個線程的join()方法,join不加參數的時候結果如下:
解釋:
func1 在3s 之後結束,fun2 在5s之後結束,并且最後輸出 【end join】
代碼二
time.sleep(8)
thd.join(2)
在join()函數添加參數 2 ,表示等待兩秒,結果如下
兩個線程開始并發執行,先執行func1的join(2),等func1執行2s後,執行func2的join(2),等線程2執行2s後,開始執行主程序,列印「end join」,1s之後fun2執行結束。
這裡join(2)标示2s之後不管目前線程是否執行完成,都會處理下一個線程。
總結一下:
1 join方法的作用是阻塞主程序無法執行join以後的語句,專注執行多線程,必須等待多線程執行完畢之後才能執行主線程的語句。
2 多線程多join的情況下,依次執行各線程的join方法,前一個結束之後,才能執行後一個。
3 無參數,則等待到該線程結束,才開始執行下一個線程的join。
4 設定參數後,則等待該線程N秒之後不管該線程是否結束,就開始執行後面的主程序。