1. 程式人生 > >多線程實現生產者消費者

多線程實現生產者消費者

sum sel item __main__ sleep port start per read

 1 import threading
 2 import random
 3 import queue
 4 import time
 5 
 6 
 7 class Producer(threading.Thread):
 8     def __init__(self, que):
 9         super().__init__()
10         self.que = que
11 
12     def run(self):
13         while True:
14             data = random.randint(0, 100)
15             print
("生產者生產了:", data) 16 self.que.put(data) 17 time.sleep(1) 18 19 20 class Consumer(threading.Thread): 21 def __init__(self, que): 22 super().__init__() 23 self.que = que 24 25 def run(self): 26 while True: 27 item = self.que.get() 28
print("消費者消費了:", item) 29 30 31 if __name__ == __main__: 32 q = queue.Queue() 33 pro = Producer(q) 34 con = Consumer(q) 35 pro.start() 36 con.start() 37 pro.join() 38 con.join()

多線程實現生產者消費者