queue模块的Queue对象实现了多生产者/多消费者队列,尤其适合需要在多个线程之间进行信息交换的场合,实现了多线程编程所需要的所有锁语义。
Queue对象主要实现了put()和get()方法,分别用来往队列尾部追加元素和在队列头部获取并删除元素。这两个方法都允许指定超时时间,其用法分别为put(item, block=True, timeout=None)和get(block=True, timeout=None)
在下面的代码中,自定义了生产者线程类和消费者线程类,生产者生产随机数量个元素并放置到队列中,消费者则从队列中依次获取其中的元素。
from threading import Thread
from time import sleep
from queue import Queue
from random import randrange
class Producer(Thread):
'''自定义生产者线程类'''
def __init__(self, threadname):
Thread.__init__(self,\
name=threadname)
def run(self):
'''线程运行代码'''
total = randrange(20)
for i in range(total):
# 等待随机时间后往队列中放入一个元素
sleep(randrange(3))
myQueue.put(i)
print(self.getName(),\
' put ', i,\
' to queue.')
# None表示生产者线程结束
myQueue.put(None)
class Consumer(Thread):
def __init__(self, threadname):
Thread.__init__(self,\
name=threadname)
def run(self):
while True:
sleep(randrange(3))
item = myQueue.get()
if item is None:
break
print(self.getName(),\
' get ', item,\
' from queue.')
# 创建队列
myQueue = Queue()
# 创建并启动生产者和消费者线程
Producer('Producer').start()
Consumer('Consumer').start()
第一次运行结果:
Producer put 0 to queue.
Producer put 1 to queue.
Producer put 2 to queue.
Producer put 3 to queue.
Producer put 4 to queue.
Consumer get 0 from queue.
Producer put 5 to queue.
Consumer get 1 from queue.
Consumer get 2 from queue.
Producer put 6 to queue.
Producer put 7 to queue.
Consumer get 3 from queue.
Consumer get 4 from queue.
Consumer get 5 from queue.
Consumer get 6 from queue.
Consumer get 7 from queue.
第二次运行结果:
Producer put 0 to queue.
Consumer get 0 from queue.
Producer put 1 to queue.
Consumer get 1 from queue.
Producer put 2 to queue.
Consumer get 2 from queue.
Producer put 3 to queue.
Consumer get 3 from queue.
Producer put 4 to queue.
Producer put 5 to queue.
Consumer get 4 from queue.
Consumer get 5 from queue.
Producer put 6 to queue.
Consumer get 6 from queue.
Producer put 7 to queue.
Consumer get 7 from queue.
Producer put 8 to queue.
Producer put 9 to queue.
Consumer get 8 from queue.
Consumer get 9 from queue.
Producer put 10 to queue.
Consumer get 10 from queue.
Producer put 11 to queue.
Consumer get 11 from queue.
标签:queue,Producer,get,Python,self,Queue,put,多线程,Consumer From: https://blog.51cto.com/u_9653244/6450944