python多线程控制
利用wait的阻塞机制, 就能够实现暂停和恢复了, 再配合循环判断标识位, 就能实现退出了
#!/usr/bin/env python # coding: utf-8 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(): self.__flag.wait() # 为True时立即返回, 为False时阻塞直到内部的标识位为True后返回 print time.time() time.sleep(1) def pause(self): self.__flag.clear() # 设置为False, 让线程阻塞 def resume(self): self.__flag.set() # 设置为True, 让线程停止阻塞 def stop(self): self.__flag.set() # 将线程从暂停状态恢复, 如何已经暂停的话 self.__running.clear() # 设置为False
测试代码
a = Job() a.start() time.sleep(3) a.pause() time.sleep(3) a.resume() time.sleep(3) a.pause() time.sleep(2) a.stop()