python多线程join/setDaemon

import threading, time

class Test():
    def test1(self):
        print("--")
        time.sleep(3)
        print("----")


    def test2(self):
        print("==")
        time.sleep(3)
        print("====")

    def run(self):
        threads = []
        t = threading.Thread(target=self.test1)
        t2 = threading.Thread(target=self.test2)
        threads.append(t)
        threads.append(t2)
        for t in threads:
            t.setDaemon(True)  # 将主线程设置为(被)守护线程,主线程结束,子线程也随之结束
            t.start()
            #t.join()
        for t in threads:
            t.join()
        print("主线程结束")
        # 1.不join,同时执行,主线程结束,等待,执行
        # 2. t.start()的for循环内join,会阻塞主进程,且下一个子线程被迫等待执行
        # 3. 另起一个for循环join,同时执行,等待,执行,主线程结束


if __name__ == "__main__":
    c = Test()
    c.run()

相关推荐