import threading import queue import time # 創建隊列,用於存儲數據 q = queue.Queue() icnt = 0 def producer(): while True: global icnt icnt = icnt + 1 #print("producer icnt is:%d "%icnt) data = "hello world" print("producer is:",icnt) q.put(data) # 生產者線程函數,向隊列存入數據 #q.join() data = "hello queue aaa " print("producer is:aaa ",icnt) q.put(data) # 生產者線程函數,向隊列存入數據 q.join() time.sleep(1) def consumer(): while True: data = q.get() # 消費者線程,從隊列取出數據 q.task_done() print("consumer is:",data) # 創建並啓動生產者、消費者線程 t1 = threading.Thread(target=producer) t2 = threading.Thread(target=consumer) t1.start() t2.start() # 等待線程結束 t1.join() t2.join()
運行結果:
producer is: 1 producer is:aaa 1 consumer is: hello world consumer is: hello queue aaa producer is: 2 producer is:aaa 2 consumer is: hello world consumer is: hello queue aaa
源碼二
import threading import queue import time # 創建隊列,用於存儲數據 q = queue.Queue() icnt = 0 def producer(): while True: global icnt icnt = icnt + 1 #print("producer icnt is:%d "%icnt) data = "hello world" print("producer is:",icnt) q.put(data) # 生產者線程函數,向隊列存入數據 q.join() data = "hello queue aaa " print("producer is:aaa ",icnt) q.put(data) # 生產者線程函數,向隊列存入數據 q.join() time.sleep(1) def consumer(): while True: data = q.get() # 消費者線程,從隊列取出數據 q.task_done() print("consumer is:",data) # 創建並啓動生產者、消費者線程 t1 = threading.Thread(target=producer) t2 = threading.Thread(target=consumer) t1.start() t2.start() # 等待線程結束 t1.join() t2.join()
運行結果:
producer is: 1 consumer is: hello world producer is:aaa 1 consumer is: hello queue aaa producer is: 2 consumer is: hello world producer is:aaa 2 consumer is: hello queue aaa