threading.active_count() 查看當前已激活的線程
threading.enumerate() 查看當前所有的線程
threading.current_thread() 查看當前線程(主線程)
threading.Thread(target=函數名)
1,當一個進程啟動之后,會默認產生一個主線程,設置多線程時,主線程會創建多個子線程,在python中,默認情況下主線程執行完自己的任務以后,就退出了,此時子線程會繼續執行自己的任務,直到自己的任務結束。
import threading as td import time def job(): time.sleep(2) print('當前線程的名字是:',td.current_thread().name) time.sleep(2) if __name__ == '__main__': start_time = time.time() thread_list = [] for i in range(5): t = td.Thread(target=job) thread_list.append(t) for t in thread_list: t.start() print('主線程結束:',td.current_thread().name) print('一共用時:',time.time()-start_time)
>>> 主線程結束: MainThread 一共用時: 0.0009999275207519531 當前線程的名字是: Thread-1當前線程的名字是: Thread-2 當前線程的名字是: Thread-3 當前線程的名字是: 當前線程的名字是:Thread-4 Thread-5
我們的計時是對主線程計時,主線程結束,計時隨之結束,打印出主線程的用時。
主線程的任務完成之后,主線程隨之結束,子線程繼續執行自己的任務,直到全部的子線程的任務全部結束,程序結束。
2,當我們使用setDaemon(True)方法,設置子線程為守護線程時,主線程一旦執行結束,則全部線程全部被終止執行,可能出現的情況就是,子線程的任務還沒有完全執行結束,就被迫停止。
import threading as td import time def job(): time.sleep(2) print('當前線程的名字是:',td.current_thread().name) time.sleep(2) if __name__ == '__main__': start_time = time.time() thread_list = [] for i in range(5): t = td.Thread(target=job) thread_list.append(t) for t in thread_list: t.setDaemon(True) t.start() print('主線程結束:',td.current_thread().name) print('一共用時:',time.time()-start_time)
>>>
主線程結束: MainThread
一共用時: 0.0009999275207519531
非常明顯的看到,主線程結束以后,子線程還沒有來得及執行,整個程序就退出了。
3,join所完成的工作就是線程同步,即主線程任務結束之后,進入阻塞狀態,一直等待其他的子線程執行結束之后,主線程在終止。
import threading as td import time def job(): time.sleep(2) print('當前線程的名字是:',td.current_thread().name) time.sleep(2) if __name__ == '__main__': start_time = time.time() thread_list = [] for i in range(5): t = td.Thread(target=job) thread_list.append(t) for t in thread_list: t.setDaemon(True) t.start() for t in thread_list: t.join() print('主線程結束:',td.current_thread().name) print('一共用時:',time.time()-start_time)
>>> 當前線程的名字是: Thread-1 當前線程的名字是: Thread-3 當前線程的名字是: Thread-4 當前線程的名字是: Thread-5 當前線程的名字是:Thread-2 主線程結束: MainThread 一共用時: 4.0012288093566895
可以看到,主線程一直等待全部的子線程結束之后,主線程自身才結束,程序退出。