python-線程五(守護、退出)


守護線程:主線程結束,無論子線程是否執行完畢,都跟着結束

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")

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM