1 import threading, time 2 3 class Test(): 4 def test1(self): 5 print("--") 6 time.sleep(3) 7 print("----") 8 9 10 def test2(self): 11 print("==") 12 time.sleep(3) 13 print("====") 14 15 def run(self): 16 threads = [] 17 t = threading.Thread(target=self.test1) 18 t2 = threading.Thread(target=self.test2) 19 threads.append(t) 20 threads.append(t2) 21 for t in threads: 22 t.setDaemon(True) # 将主线程设置为(被)守护线程,主线程结束,子线程也随之结束 23 t.start() 24 #t.join() 25 for t in threads: 26 t.join() 27 print("主线程结束") 28 # 1.不join,同时执行,主线程结束,等待,执行 29 # 2. t.start()的for循环内join,会阻塞主进程,且下一个子线程被迫等待执行 30 # 3. 另起一个for循环join,同时执行,等待,执行,主线程结束 31 32 33 if __name__ == "__main__": 34 c = Test() 35 c.run()
原文地址:https://www.cnblogs.com/yzg-14/p/12110592.html
时间: 2024-10-11 10:43:40