多线程实现生产者消费者

Posted gkl123

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了多线程实现生产者消费者相关的知识,希望对你有一定的参考价值。

 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()

 

以上是关于多线程实现生产者消费者的主要内容,如果未能解决你的问题,请参考以下文章