创建一个存放整数的队列。 创建3个生产者线程,每隔M毫秒往队列的尾部放入一个整数,所放的整数依次为1、2、3、…。 创建5个消费者线程,每隔N毫秒从队列的头部取出一个整数,并将其打印出来。 注意使用同步。
时间: 2024-05-10 09:21:40 浏览: 11
下面是一个简单的实现示例:
```python
import threading
import time
class Queue:
def __init__(self):
self.queue = []
self.lock = threading.Lock()
self.condition = threading.Condition(self.lock)
def put(self, item):
with self.lock:
self.queue.append(item)
self.condition.notify()
def get(self):
with self.lock:
while not self.queue:
self.condition.wait()
return self.queue.pop(0)
def producer(queue, interval):
i = 1
while True:
queue.put(i)
i += 1
time.sleep(interval / 1000)
def consumer(queue, interval):
while True:
item = queue.get()
print(item)
time.sleep(interval / 1000)
if __name__ == '__main__':
queue = Queue()
producers = []
consumers = []
for i in range(3):
thread = threading.Thread(target=producer, args=(queue, 1000))
producers.append(thread)
thread.start()
for i in range(5):
thread = threading.Thread(target=consumer, args=(queue, 2000))
consumers.append(thread)
thread.start()
for thread in producers:
thread.join()
for thread in consumers:
thread.join()
```
这个实现中,`Queue` 类是一个简单的队列,使用了 `threading.Lock` 和 `threading.Condition` 进行同步。`put` 和 `get` 方法都是同步的。其中,`put` 方法在往队列中添加新元素时需要先获得锁,然后添加元素并通过 `condition.notify()` 通知等待的线程;`get` 方法在从队列中取出元素时需要先判断队列是否为空,如果为空则通过 `condition.wait()` 等待其他线程添加元素,并在有新元素时返回队列的头部元素。
`producer` 和 `consumer` 分别是生产者和消费者线程的函数。每个生产者线程都会每隔 `interval` 毫秒往队列中添加一个整数,初始值为 1,然后每次加 1。每个消费者线程都会每隔 `interval` 毫秒从队列头部取出一个整数,并打印出来。
在主程序中,首先创建了一个 `Queue` 对象,然后创建了 3 个生产者线程和 5 个消费者线程,并启动它们。最后,等待所有线程结束。