python,用event方法实现线程间通信控制
import threading,time class Boss(threading.Thread): def run(self): print("We must work today!") event.isSet() or event.set() time.sleep(5) print("You can go home right now!") event.isSet() or event.set() class Worker(threading.Thread): def run(self): event.wait() print("Oh,my god!!!") time.sleep(1) event.clear() event.wait() print("Oh,yeah!!!") if __name__ == "__main__": event = threading.Event() threads = [] for i in range(5): threads.append(Worker()) threads.append(Boss()) for t in threads: t.start() for t in threads: t.join()
运行后显示:
We must work today!
Oh,my god!!!
Oh,my god!!!
Oh,my god!!!
Oh,my god!!!
Oh,my god!!!
You can go home right now!
Oh,yeah!!!
Oh,yeah!!!
Oh,yeah!!!
Oh,yeah!!!
Oh,yeah!!!
Process finished with exit code 0