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