1 import threading 2 #定義線程要調用的方法,*add可接收多個以非關鍵字方式傳入的參數 3 def action(*add): 4 for arc in add: 5 #調用 getName() 方法獲取當前執行該程序的線程名 6 print(threading.current_thread().getName() +" "+ arc) 7 #定義為線程方法傳入的參數 8 my_tuple = ("http://c.biancheng.net/python/",\ 9 "http://c.biancheng.net/shell/",\ 10 "http://c.biancheng.net/java/") 11 #創建線程 12 thread = threading.Thread(target = action,args =my_tuple) 13 #啟動線程 14 thread.start() 15 #主線程執行如下語句 16 for i in range(5): 17 print(threading.current_thread().getName())
程序執行結果為(不唯一):
Thread-1 http://c.biancheng.net/python/MainThread
Thread-1 http://c.biancheng.net/shell/MainThread
Thread-1 http://c.biancheng.net/java/MainThread
MainThread
MainThread
可以看到,我們用 Thread 類創建了一個線程(線程名為 Thread-1),其任務是執行 action() 函數。同時,我們也給主線程 MainThread 安排了循環任務(第 16、17 行)。通過前面的學習我們知道,主線程 MainThread 和子線程 Thread-1 會輪流獲得 CPU 資源,因此該程序的輸出結果才會向上面顯示的這樣。
但是,如果我們想讓 Thread-1 子線程先執行,然后再讓 MainThread 執行第 16、17 行代碼,該如何實現呢?很簡單,通過調用線程對象的 join() 方法即可。
join() 方法的功能是在程序指定位置,優先讓該方法的調用者使用 CPU 資源。該方法的語法格式如下:
thread.join( [timeout] )
其中,thread 為 Thread 類或其子類的實例化對象;timeout 參數作為可選參數,其功能是指定 thread 線程最多可以霸占 CPU 資源的時間(以秒為單位),如果省略,則默認直到 thread 執行結束(進入死亡狀態)才釋放 CPU 資源。
舉個例子,修改上面的代碼,如下所示:
1 import threading 2 #定義線程要調用的方法,*add可接收多個以非關鍵字方式傳入的參數 3 def action(*add): 4 for arc in add: 5 #調用 getName() 方法獲取當前執行該程序的線程名 6 print(threading.current_thread().getName() +" "+ arc) 7 #定義為線程方法傳入的參數 8 my_tuple = ("http://c.biancheng.net/python/",\ 9 "http://c.biancheng.net/shell/",\ 10 "http://c.biancheng.net/java/") 11 #創建線程 12 thread = threading.Thread(target = action,args =my_tuple) 13 #啟動線程 14 thread.start() 15 #指定 thread 線程優先執行完畢 16 thread.join() 17 #主線程執行如下語句 18 for i in range(5): 19 print(threading.current_thread().getName())
程序執行結果為:
Thread-1 http://c.biancheng.net/python/
Thread-1 http://c.biancheng.net/shell/
Thread-1 http://c.biancheng.net/java/
MainThread
MainThread
MainThread
MainThread
MainThread
程序中第 16 行的位置,thread 線程調用了 join() 方法,並且沒有指定具體的 timeout 參數值。這意味着如果程序想繼續往下執行,必須先執行完 thread 線程。