在python中编程实现红绿灯_python多线程Event实现红绿灯案例

代码:

# __author__ = 'STEVEN'

# coding = utf-8

import time,threading

#开启事件

event = threading.Event()

count = 0

class 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()

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值