Python: 多線程join

 視頻地址:https://www.bilibili.com/video/av16944429?p=3

1: join所完成的工作就是線程同步,即主線程任務結束之後,進入阻塞狀態,一直等待其他的子線程執行結束之後,主線程在終止

2::默認情況下(其實就是setDaemon(False)),主線程執行完自己的任務以後,就退出了;

代碼例子:

import threading
import time

def run():

    time.sleep(2)
    print('當前線程的名字是: ', threading.current_thread().name)
    time.sleep(2)


if __name__ == '__main__':

    start_time = time.time()

    print('這是主線程:', threading.current_thread().name)
    thread_list = []
    for i in range(5):
        t = threading.Thread(target=run)
        thread_list.append(t)

    for t in thread_list:
        t.setDaemon(True)
        t.start()

    for t in thread_list:
        t.join()

    print('主線程結束了!' , threading.current_thread().name)
    print('一共用時:', time.time()-start_time)

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章