首页 > 编程语言 > 详细

python-线程五(守护、退出)

时间:2020-03-28 20:55:46      阅读:62      评论:0      收藏:0      [点我收藏+]

守护线程:主线程结束,无论子线程是否执行完毕,都跟着结束

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

 

python-线程五(守护、退出)

原文:https://www.cnblogs.com/su-sir/p/12589054.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!