python 歸納 (十四)_隊列Queue實現生產者消費者

來源:互聯網
上載者:User

標籤:類構造   pytho   while   end   double   self   art   建立   python   

# -*- coding: UTF-8 -*-"""多線程的生產者,消費者使用隊列Queue"""import Queueimport threadingimport timeimport randomqueue = Queue.Queue(3)  # 建立3個大小的隊列class Producer(threading.Thread):    """    生產者,往隊列中寫資料    """    def __init__(self, queue):        super(Producer, self).__init__()  # 調用父類建構函式        self.queue = queue    def run(self):        while True:            my_rand_double = random.random()            self.queue.put(my_rand_double)      # 往隊列寫資料            print "producer randonm %f \n" % (my_rand_double)            time.sleep(2)class Consumer(threading.Thread):    """    消費者,從隊列中讀取資料    """    def __init__(self, queue):        super(Consumer, self).__init__()        self.queue = queue    def run(self):        while True:            my_data = self.queue.get()          # 從隊列讀資料            print "consumer:",my_data,"\n"            time.sleep(1)if __name__ == ‘__main__‘:    print "begin....\n"    # 啟動線程    Producer(queue).start()    Consumer(queue).start()    Consumer(queue).start()    print "main end....\n""""Out:begin....producer randonm 0.321120consumer: 0.32111958348main end....producer randonm 0.340942consumer: 0.340942161065producer randonm 0.672640consumer: 0.672639677729producer randonm 0.940307consumer: 0.940307007999producer randonm 0.497011consumer: 0.497011018834"""

 

python 歸納 (十四)_隊列Queue實現生產者消費者

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.