红绿灯例子
Event的用法文章来源:https://www.toymoban.com/news/detail-654173.html
import threading,time
event=threading.Event()
def lighter():
timesec=0
event.set()
while True:
if 5<timesec<=10:
event.clear()
print("红灯亮")
elif timesec>10:
event.set()
timesec=0
else:
print("绿灯亮")
time.sleep(1)
timesec+=1
def car(name):
while True:
if event.is_set():
print(f"{name}正在行驶...")
time.sleep(1)
else:
print(f"{name}看红灯亮")
event.wait()
print(f"--{name}绿灯亮")
light=threading.Thread(target=lighter,)
light.start()
car=threading.Thread(target=car,args=('mini',))
car.start()
等同方案:文章来源地址https://www.toymoban.com/news/detail-654173.html
import threading,time
event=False #Event
def lighter():
timesec=0
global event
event=True
while True:
if 5<timesec<=10:
event=False #event.clear()
print("-红灯亮")
else: #可以用elif那部分 ,这放在了下面if中
if timesec>10:
event=True #相当于event.set()
timesec=0
print("-绿灯亮")
time.sleep(1)
timesec+=1
def car(name):
global event
while True:
if event: #相当于event.is_set()
print(f"{name}正在行驶...")
else:
print(f"{name}看红灯亮")
while not event: #替换event.wait()
if event:
break
time.sleep(0.5)
print(f"{name}看绿灯亮")
time.sleep(1)
light=threading.Thread(target=lighter,)
light.start()
car=threading.Thread(target=car,args=('mini',))
car.start()
到了这里,关于python threading.Event()用法的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!