python threading 停止和暂停线程

python的threading包,暂停线程、恢复线程,和停止线程的方法

import threading
import time


class Job(threading.Thread):

    def __init__(self, *args, **kwargs):
        super(Job, self).__init__(*args, **kwargs)
        self.__flag = threading.Event()  # 用于暂停线程的标识
        self.__flag.set()  # 设置为True
        self.__running = threading.Event()  # 用于停止线程的标识
        self.__running.set()  # 将running设置为True

    def run(self):
        while self.__running.isSet():
            print("thread is run")
            self.__flag.wait()  # 为True时立即返回, 为False时阻塞直到self.__flag为True后返回
            print("run = ",time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()))
            time.sleep(1)

    def pause(self):
        print("thread is pause")
        self.__flag.clear()  # 设置为False, 让线程阻塞

    def resume(self):
        print("thread is resume")
        self.__flag.set()  # 设置为True, 让线程停止阻塞

    def stop(self):
        print("thread is stop")
        self.__flag.set()  # 将线程从暂停状态恢复, 如何已经暂停的话
        self.__running.clear()  # 设置为False


a = Job()
a.start()
time.sleep(3)
a.pause()
time.sleep(5)
a.resume()
time.sleep(2)
a.stop()

你可能感兴趣的:(python学习记录,python,开发语言)