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() 相关推荐
elizabethxxy 2020-11-06
pythonxuexi 2020-10-30
retacnyue 2020-09-28
pythonxuexi 2020-09-06
Morelia 2020-09-04
zhaobig 2020-08-17
linkequa 2020-08-16
CloudXli 2020-08-14
kikaylee 2020-08-12
LowisLucifer 2020-08-09
xiesheng 2020-08-06
Tristahong 2020-08-05
CatherineC00 2020-08-01
Andrewjdw 2020-07-26
reallyr 2020-07-18
wordmhg 2020-07-16
yawei 2020-07-06
zlfing 2020-07-07