守護線程:主線程結束,無論子線程是否執行完畢,都跟着結束
import threading import time class MyThread(threading.Thread): def __init__(self, id): super().__init__() self.id = id def run(self): time.sleep(5) print("This is " + self.getName()) # 獲取進程的名稱 if __name__ == "__main__": t1 = MyThread(999) t1.setDaemon(True) # 將子線程設置為守護線程 t1.start() print("I am the father thread.")
退出:子線程可以主動退出運行
import threading import time import _thread exitFlag = 0 # 是否每個線程要進行工作后再退出,設定1則所有線程啟動后直接退出 class myThread (threading.Thread): # 繼承父類threading.Thread def __init__(self, threadID, name, counter): super().__init__() # self.threadID = threadID self.name = name self.counter = counter def run(self): # 把要執行的代碼寫到run函數里面線程在創建后會直接運行run函數 print("Starting " + self.name) print_time(self.name, 5, self.counter) print("Exiting " + self.name) def print_time(threadName, delay, counter): while counter: if exitFlag: _thread.exit() # 這個是讓線程主動退出 time.sleep(delay) print("%s: %s" % (threadName, time.ctime(time.time()))) counter -= 1 # 創建新線程 thread1 = myThread(1, "Thread-1", 1) thread2 = myThread(2, "Thread-2", 2) # 開啟線程 thread1.start() thread2.start() print("Exiting Main Thread")