例子:
import threading
import time
def test1():
? ? for iin range(5):
? ? ? ? print("-----test1----%d---" % i)
? ? ? ? time. sleep(1)
# 如果創(chuàng)建 Thread 時(shí)執(zhí)行的函數(shù),運(yùn)行結(jié)束那么意味著這個(gè)子線程結(jié)束了
def test2():
? ? for iin range(10):
? ? ? ? print("-----test2----%d---" % i)
? ? ? ? time. sleep(1)
def main():
? ? t1= threading.Thread(target=test1)? # 定義第 1 個(gè)線程
? ? t2= threading.Thread(target=test2)? # 定義第 2 個(gè)線程
? ? t1.start()? # 子線程 1 開始運(yùn)行
? ? t2.start()? # 子線程 2 開始運(yùn)行
while True:
? ? print(threading.enumerate())? # 打印所有線程信息
? ? if len(threading.enumerate()) <= 1:
? ? ? ? break
? ? time. sleep(1)
if __name__== '__main__':
? ? main()
總結(jié)
雖然線程間的運(yùn)行是無序的蟋软,但是主線程會等待子線程結(jié)束侦铜,然后再結(jié)束。
若是一個(gè)程序的主線程被殺死钟鸵,那么子線程也必定會結(jié)束钉稍。