threading.Event类内置了两个成员:
self._cond = Condition(Lock()) 这是一个条件同步线程,用于wait和noticeall
self._flag = False 这个值,默认是False,如果是False,线程进行到wait函数是会阻塞,如果是True,有wait函数的线程解除阻塞,并且在运行到wait函数时如果还是True,这个时候不会阻塞,所以一般在wait后的代码执行完成后,应紧跟event.clear()
threading.Event有4种方法:
Event.wait()
Event.set()
Event.clear()
Event.isSet()
set函数将self._flag值设置为True ,clear函数将self._flag值设置为False,isSet判断self._flag值是True还是False
import time import threading import sys event = threading.Event() action = 'parse' class Plane(threading.Thread): def __init__(self, name, x, y): threading.Thread.__init__(self, name=name, args=(x, y)) self.pix = [x, y] def run(self): global action while action != 's': event.wait() if action == 'l': self.left() elif action == 'r': self.right() elif action == 'u': self.up() elif action == 'd': self.down() event.clear() def left(self): self.pix[0] -= 1 sys.stdout.write(f'{self.name}:{self.pix}\n') def right(self): self.pix[0] += 1 sys.stdout.write(f'{self.name}:{self.pix}\n') def up(self): self.pix[1] -= 1 sys.stdout.write(f'{self.name}:{self.pix}\n') def down(self): self.pix[1] += 1 sys.stdout.write(f'{self.name}:{self.pix}\n') if __name__ == '__main__': threads = [] for i in range(1, 6): threads.append(Plane('Plane' + str(i), 100, 100)) for t in threads: t.setDaemon(True) # 设置子线程为守护,即主线程结束则跟着结束 t.start() ipt = 'ok' print(ipt) while ipt != 'exit': ipt = input('请输入方向:') action = ipt.strip() event.set() time.sleep(0.2) else: action = 's' # event.set() print("完毕")