標籤:類構造 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實現生產者消費者