#coding:utf-8 import threading import time def producer(): print u‘tantianran: 等人来买包子...‘ event.wait() #一开始为阻塞,如果检测到标志位被设置成了true(标志位默认是flase),则继续往下执行 event.clear() #将标志位设置回flase print u‘tantianran: 生产包子中...‘ time.sleep(5) print u‘tantianran: 催你妹啊!你的包子做好了...‘ event.set() # 设置标志位为true,通知线程t2,包子做好了 def consumer(): print u‘tanzhenxing: 去买包子...‘ event.set() #设置标志位为true,通知t1线程要去买包子 time.sleep(2) while True: if event.isSet(): print u‘tanzhenxing: 买到包子了,包子真好吃...谢谢!‘ break else: print u‘tanzhenxing: 包子还尼马没做好?‘ time.sleep(2) if __name__ == ‘__main__‘: event = threading.Event() t1 = threading.Thread(target=producer) t2 = threading.Thread(target=consumer) t1.start() t2.start()
执行结果:
/usr/bin/python2.7 /home/toby/PycharmProjects/test-20170419/01.py
tantianran: 等人来买包子...
tanzhenxing: 去买包子...
tantianran: 生产包子中...
tanzhenxing: 包子还尼马没做好?
tanzhenxing: 包子还尼马没做好?
tantianran: 催你妹啊!你的包子做好了...
tanzhenxing: 买到包子了,包子真好吃...谢谢!
时间: 2024-10-13 16:42:40