Join()同时等待非守护进程和守护进程线程完成。
如果没有join(),将运行非守护进程线程,并与主线程并发完成。
如果没有join(),守护线程将与主线程并发运行,当主线程完成时,如果守护线程仍在运行,守护线程将在未完成的情况下退出。
因此,下面的join()和daemon=False(守护线程)(daemon默认为False):
import time
from threading import Thread
def test1():
for _ in range(3):
print("Test1 is running...")
time.sleep(1)
print("Test1 is completed")
def test2():
for _ in range(3):
print("Test2 is running...")
time.sleep(1)
print("Test2 is completed")
# Here
thread1 = Thread(target=test1, daemon=False)
thread2 = Thread(target=test2, daemon=False)
# Here
thread1.start()
thread2.start()
thread1.join() # Here
thread2.join() # Here
print("Main is completed")
或者,使用join()和daemon=True(非守护线程):
# ...
# Here
thread1 = Thread(target=test1, daemon=True)
thread2 = Thread(target=test2, daemon=True)
# Here
# ...
thread1.join() # Here
thread2.join() # Here
print("Main is completed")
join()等待Test1和Test2非守护进程或守护进程线程完成。因此,Main is completed在Test1和Test2线程完成后打印,如下所示:
Test1 is running...
Test2 is running...
Test1 is running...
Test2 is running...
Test1 is running...
Test2 is running...
Test1 is completed
Test2 is completed
Main is completed
并且,如果不使用join(),如果daemon=False(非守护线程):
# ...
# Here
thread1 = Thread(target=test1, daemon=False)
thread2 = Thread(target=test2, daemon=False)
# Here
# ...
# thread1.join()
# thread2.join()
print("Main is completed")
Test1和Test2非守护线程正在与主线程并发地运行和完成。因此,Main is completed在Test1和Test2线程完成之前打印,如下所示:
Test1 is running...
Test2 is running...
Main is completed
Test1 is running...
Test2 is running...
Test1 is running...
Test2 is running...
Test1 is completed
Test2 is completed
并且,如果没有使用join(),如果daemon=True(守护线程):
# ...
# Here
thread1 = Thread(target=test1, daemon=True)
thread2 = Thread(target=test2, daemon=True)
# Here
# ...
# thread1.join()
# thread2.join()
print("Main is completed")
Test1和Test2守护线程与主线程并发运行。因此,Main is completed在Test1和Test2守护线程完成之前打印,当主线程完成时,Test1和Test2守护线程将在未完成的情况下退出,如下所示:
Test1 is running...
Test2 is running...
Main is completed