红绿灯模型

import time,threading

event = threading.Event()

def lighter():
count = 0
event.set()#先设置绿灯
while True:
if 5 < count and count < 10:
event.clear()#把标志位清了
print("red light is on")
elif count > 10:
event.set()#变绿灯
print("green light is on")
count = 0
else:
print("green light is on")
time.sleep(1)
count += 1

def car(name):
while True:
if event.is_set():#代表绿灯
print("%s running"%name)
time.sleep(1)
else:
print("%s see the light is red ,waitting"%name)
event.wait()
print("%s see the light is green , going"%name)

light = threading.Thread(target=lighter,)
light.start()

car1 = threading.Thread(target=car,args=("tesla",))
car1.start()



posted @ 2017-12-09 23:06  cerofang  阅读(472)  评论(0编辑  收藏  举报