python多線程Event實現紅綠燈案例

來源:互聯網
上載者:User

標籤: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實現紅綠燈案例

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.