1. join
用于阻塞主线程,直到子线程完成或阻塞主线程超时,主线程继续往下执行。
# 1.直到子线程完成,主线程继续往下执行。
import time
import threading
def my_thread():
print("my_thread_start")
time.sleep(2)
print("my_thread_end")
thread0 = threading.Thread(target=my_thread)
print("====main_thread====")
thread0.start()
thread0.join(3)
print("====main_thread====")
"""
运行结果:
====main_thread====
my_thread_start
my_thread_end
====main_thread====
Process finished with exit code 0
"""
# 直到阻塞主线程超时,主线程继续往下执行。
import time
import threading
def my_thread():
print("my_thread_start")
time.sleep(2)
print("my_thread_end")
thread0 = threading.Thread(target=my_thread)
print("====main_thread====")
thread0.start()
thread0.join(1)
print("====main_thread====")
"""
运行结果:
====main_thread====
my_thread_start
====main_thread====
my_thread_end
Process finished with exit code 0
"""
2. setDaemon
将子线程设置为守护线程,在主线程完成退出时,子线程不论是否完成,跟着主线程一块退出。
import time
import threading
def my_thread():
print("my_thread_start")
time.sleep(2)
print("my_thread_end")
thread0 = threading.Thread(target=my_thread)
print("====main_thread====")
thread0.setDaemon(daemonic=True)
thread0.start()
print("====main_thread====")
"""
运行结果:
====main_thread====
my_thread_start
====main_thread====
Process finished with exit code 0
"""