1 import threading, time 2 def Myjoin(): 3 print 'hello world!' 4 time.sleep(1) 5 for i in range(5): 6 t=threading.Thread(target=Myjoin) 7 t.start() 8 t.join() 9 print 'hello main' 10 #輸出:(每隔一秒輸出) 11 hello world! 12 hello world! 13 hello world! 14 hello world! 15 hello world! 16 hello main 17 注釋掉join 18 #輸出: 19 hello world! 20 hello world!hello world! 21 22 hello world! 23 hello world!hello main 24 (全部輸出后等待一秒程序結束)
所以join的作用是保證當前線程執行完成后,再執行其它線程。join可以有timeout參數,表示阻塞其它線程timeout秒后,不再阻塞。詳見官方文檔。