python线程----Event事件

事件

红绿灯线程事件代码

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

运行结果:
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值