python实现一段代码,解决生产者,消费者问题
时间: 2023-06-05 10:07:22 浏览: 127
好的,以下是一段 Python 实现的生产者消费者问题解决方案:
``` python
import threading
import random
import time
queue = []
MAX_NUM = 10
class ProducerThread(threading.Thread):
def run(self):
global queue
while True:
num = random.randint(1, MAX_NUM)
print("Produced ===> ", num)
queue.append(num)
time.sleep(random.random())
class ConsumerThread(threading.Thread):
def run(self):
global queue
while True:
if not queue:
print("Nothing in queue, consumer is waiting...")
time.sleep(random.random())
continue
num = queue.pop(0)
print("Consumed <=== ", num)
time.sleep(random.random())
ProducerThread().start()
ConsumerThread().start()
```
这段代码实现了多线程生产者消费者任务。其中,生产者会随机产生数字并添加到队列中,而消费者则从队列中取出数字。如果队列为空,则消费者会等待。
阅读全文