# Python queue隊列,實現並發,在網站多線程推薦最后也一個例子,比這貨簡單,但是不夠規范 # encoding: utf-8 __author__ = 'yeayee.com' # 由本站增加注釋,可隨意Fork、Copy from queue import Queue # Queue在3.x中改成了queue import random import threading import time class Producer(threading.Thread): """ Producer thread 制作線程 """ def __init__(self, t_name, queue): # 傳入線程名、實例化隊列 threading.Thread.__init__(self, name=t_name) # t_name即是threadName self.data = queue """ run方法 和start方法: 它們都是從Thread繼承而來的,run()方法將在線程開啟后執行, 可以把相關的邏輯寫到run方法中(通常把run方法稱為活動[Activity]); start()方法用於啟動線程。 """ def run(self): for i in range(5): # 生成0-4五條隊列 print("%s: %s is producing %d to the queue!" % (time.ctime(), self.getName(), i)) # 當前時間t生成編號d並加入隊列 self.data.put(i) # 寫入隊列編號 time.sleep(random.randrange(10) / 5) # 隨機休息一會 print("%s: %s producing finished!" % (time.ctime(), self.getName)) # 編號d隊列完成制作 class Consumer(threading.Thread): """ Consumer thread 消費線程,感覺來源於COOKBOOK """ def __init__(self, t_name, queue): threading.Thread.__init__(self, name=t_name) self.data = queue def run(self): for i in range(5): val = self.data.get() print("%s: %s is consuming. %d in the queue is consumed!" % (time.ctime(), self.getName(), val)) # 編號d隊列已經被消費 time.sleep(random.randrange(10)) print("%s: %s consuming finished!" % (time.ctime(), self.getName())) # 編號d隊列完成消費 def main(): """ Main thread 主線程 """ queue = Queue() # 隊列實例化 producer = Producer('Pro.', queue) # 調用對象,並傳如參數線程名、實例化隊列 consumer = Consumer('Con.', queue) # 同上,在制造的同時進行消費 producer.start() # 開始制造 consumer.start() # 開始消費 """ join()的作用是,在子線程完成運行之前,這個子線程的父線程將一直被阻塞。 join()方法的位置是在for循環外的,也就是說必須等待for循環里的兩個進程都結束后,才去執行主進程。 """ producer.join() consumer.join() print('All threads terminate!') if __name__ == '__main__': main() """運行結果: Thu Feb 4 11:05:48 2016: Pro. is producing 0 to the queue! Thu Feb 4 11:05:48 2016: Pro. is producing 1 to the queue! Thu Feb 4 11:05:48 2016: Con. is consuming. 0 in the queue is consumed! Thu Feb 4 11:05:49 2016: Pro. is producing 2 to the queue! Thu Feb 4 11:05:50 2016: Pro. is producing 3 to the queue! Thu Feb 4 11:05:51 2016: Pro. is producing 4 to the queue! Thu Feb 4 11:05:52 2016: Con. is consuming. 1 in the queue is consumed! Thu Feb 4 11:05:53 2016: <bound method Producer.getName of <Producer(Pro., started 6864)>> producing finished! Thu Feb 4 11:06:00 2016: Con. is consuming. 2 in the queue is consumed! Thu Feb 4 11:06:06 2016: Con. is consuming. 3 in the queue is consumed! Thu Feb 4 11:06:06 2016: Con. is consuming. 4 in the queue is consumed! Thu Feb 4 11:06:12 2016: Con. consuming finished! All threads terminate! """