import threading,time
event=threading.Event() #生成一個event對象
def lighter():
count=0
event.set()#開始設置標志位 綠燈 設置了標志位程序就通行
while True:
if count>5 and count<10:#改成紅燈 6~9為紅燈
event.clear() #把標志位清了
print("\033[41;1mred light is on ...\033[0m")
elif count>10:
event.set()#變綠燈 設置標志位
count = 0 #count清零 重新開始
else:
print("\033[42;1mgreen light is on ...\033[0m") #0~5位綠燈
time.sleep(1) #每隔一秒記一次
count +=1
def car(name):
while True:
if event.is_set(): #is_set 判斷是否設置標志位 設置了標志位為綠燈 通行
print("[%s] running..."%name)
time.sleep(1)
else:
print("[%s] sees red light,waiting..."%name)
event.wait() #wait卡住,等待標志位被設定 等到標志位設定之后程序再往下走
print("\033[34;1m[%s] green light is on,start going...\033[34;0m"%name)
light=threading.Thread(target=lighter,)
light.start()
car1=threading.Thread(target=car,args=("Honda",))
car1.start()
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。