from queue import Queue import random import threading import time
class Producer(threading.Thread): def init(self, t_name, queue): threading.Thread.init(self, name=t_name) self.data = queue
def run(self):
for i in range(5):
print("%s: %s is producing %d to the queue!" % (time.ctime(), self.getName(), i))
self.data.put(i)
time.sleep(random.randrange(10) / 5)
print("%s: %s finished!" % (time.ctime(), self.getName()))
class Consumer(threading.Thread): def init(self, t_name, queue): threading.Thread.init(self, name=t_name) self.data = queue
def run(self):
for i in range(5):
val = self.data.get()
print("%s: %s is consuming. %d in the queue is consumed!" % (time.ctime(), self.getName(), val))
time.sleep(random.randrange(10))
print("%s: %s finished!" % (time.ctime(), self.getName()))
def main(): queue = Queue() producer = Producer('Pro.', queue) consumer = Consumer('Con.', queue) producer.start() consumer.start() producer.join() consumer.join() print('All threads terminate!')
if name == 'main': main()
import queue
q = queue.Queue(3) # 调用构造函数,初始化一个大小为3的队列 print(q.empty()) # 判断队列是否为空,也就是队列中是否有数据
q.put(13, block=True, timeout=5) print(q.full()) # 判断队列是否满了,这里我们队列初始化的大小为3 print(q.qsize()) # 获取队列当前数据的个数
print(q.get(block=True, timeout=None))
q.put_nowait(23) # 相当于q.put(23, block=False) q.get_nowait() # 相当于q.get(block=False)