標籤:glob python多線程 print 多線程 sleep elf 線程 gre nbsp
代碼:
# __author__ = ‘STEVEN‘# coding = utf-8import time,threading#開啟事件event = threading.Event()count = 0class Lighter(threading.Thread): def run(self): while True: global count count += 1 time.sleep(0.4) event.set() #設定綠燈時間為10s,紅燈為10s if count>10 and count<=20: event.clear() print(‘\033[41;1m red light ..\033[0m‘) elif count > 20: count = 0 event.set() print(‘\033[42;1m green light ..\033[0m‘) else: print(‘\033[42;1m green light ..\033[0m‘)class Car(threading.Thread): def __init__(self,name): super(Car,self).__init__() self.name = name def run(self): time.sleep(0.5) if event.is_set(): print(‘{} passed the light‘.format(self.name)) else: print(‘{} is waiting the green light‘.format(self.name))l = Lighter()l.start()#啟動50輛車,讓他們經過紅綠燈for i in range(50): time.sleep(1) c = Car(‘car{}‘.format(i)) c.start()
python多線程Event實現紅綠燈案例