事件
红绿灯线程事件代码
import threading,time
class Main(object):
event=threading.Event()
def __init__(self):
pass
def main(self):
light=light_thread()
light.start()
car1=Car("奥迪F")
car1.start()
pass
class light_thread(threading.Thread):
def __init__(self):
super(light_thread,self).__init__()
pass
def run(self):
count=0
Main.event.set() #设置开始为绿灯
while True:
if count>5 and count<10: #红灯
Main.event.clear() #清空标志位
print("\033[41;1mred light is on....\033[0m")
elif count > 10 :
Main.event.set() #变绿灯
count=0
else:
print("\033[42;1mgreen light is on....\033[0m")
time.sleep(1)
count+=1
class Car(threading.Thread):
def __init__(self,Cname):
super(Car,self).__init__()
self.cname=Cname
pass
def run(self):
while True:
if Main.event.is_set(): #代表绿灯
print("\033[31;1m[%s] is run..."%self.cname)
time.sleep(1)
else:
print("\033[28;1m[%s] sees red light,waiting..."%self.cname)
Main.event.wait()
print("\033[34;1m[%s] green light is on,start going...")
if __name__ == '__main__':
Main().main()
运行结果: