队列介绍
- 队列:队列(Queue)是一种先进先出(FIFO, First In First Out)的线性数据结构。你可以把它想象成排队买票:先来的人先买到,后来的人排在队尾;当多个线程交换信息时队列中尤其有用;---一个容器。
- 队列作用:提升效率和程序解耦;
- 队列分类:
- 先进先出对列(FIFO),如queue.Queue();
- 后进先出:如queue.LifoQueue();
- 双端队列(Deque):两端都可以入队和出队。既可以当队列用,也可以当栈用。如collections.deque;
- 优先队列(Priority Queue):出对顺序按照优先级,如queue.PriorityQueue();
- 消息队列(Message Queue): RabbitMQ、Kafka、ActiveMQ,用于系统通信。
- 阻塞队列(Blocking Queue):当队列为空时,出队操作会阻塞,直到有元素。当队列满时,入队操作会阻塞,直到有空位,如queue.Queue 就是阻塞队列,常用于生产者-消费者模型;
队列使用(测试使用参数化)
- 先入先出队列使用:
python
import queue
q=queue.Queue()
q.put("d") #存数据
q.put("f")
# q.get(block=False) #阻塞,报queue.Empty
# q.get(timeout=1) #超时,报queue.Empty异常
while True:
if q.empty(): # if q.qsize()==0:
print("队列中没有数据了")
break
else:
print(q.get()) #取数据
print(q.qsize()) #队列大小,取一个减少一个
- 优先级队列的使用:按优先级高的先取。
python
import queue
qp=queue.PriorityQueue()
qp.put((-1,"lily")) #存数据时设置优先级
qp.put((-2,"wenwen"))
qp.put((1,"baoqiang"))
qp.put((11,"wangcai"))
while True:
if qp.qsize()==0:
print("数据为空了")
break
else:
print(qp.get())
测试结果:

- 后入先出队列的使用:如买水果后进入的新鲜水果先卖出去。

- 双端对列:进入(左和右)appendleft和append。出:popleft和pop。

- 消费者模型:分为生产数据的线程端和消费数据的线程端。两个线程一个管生产一个管消费。具体见代码
python
import threading,time
import queue
q=queue.Queue(maxsize=10)
def Producer(name): #生产者端
count=1
while True:
q.put("苹果%s"%count)
print("%s进货了苹果数量%s"%(name,count))
count +=1
time.sleep(0.5)
def Customer(name): #消费者端
while True:
print("[%s]拿到了[%s],吃了他----"%(name,q.get()))
time.sleep(0.6)
if q.qsize() == 0:
print("苹果吃完了")
break
#线程
p=threading.Thread(target=Producer,args=("王林",))
c1=threading.Thread(target=Customer,args=("消费者大林",))
c2=threading.Thread(target=Customer,args=("消费者大橙子",))
#启动
p.start()
c1.start()
c2.start()
测试结果:
