使用Deque创建一个存放整数的队列。 创建一个生产者线程,每隔M毫秒往队列的尾部加入一个整数,所放的整数依次为1、2、3、…。 创建2个消费者线程,每隔N毫秒从队列的头部取出一个整数,并将其打印出来。
时间: 2024-05-05 09:15:10 浏览: 13
```python
from collections import deque
import threading
import time
queue = deque()
def producer():
num = 1
while True:
queue.append(num)
print("生产者生产了一个整数:", num)
num += 1
time.sleep(0.001)
def consumer1():
while True:
if queue:
num = queue.popleft()
print("消费者1消费了一个整数:", num)
time.sleep(0.01)
def consumer2():
while True:
if queue:
num = queue.popleft()
print("消费者2消费了一个整数:", num)
time.sleep(0.01)
if __name__ == '__main__':
producer_thread = threading.Thread(target=producer)
consumer_thread1 = threading.Thread(target=consumer1)
consumer_thread2 = threading.Thread(target=consumer2)
producer_thread.start()
consumer_thread1.start()
consumer_thread2.start()
producer_thread.join()
consumer_thread1.join()
consumer_thread2.join()
```
其中,M和N可以根据需要进行调整。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)