利用Queue对象先进先出的特性,将每个生产者的数据一次存入队列,而每个消费者将依次从队列中取出数据
import threading # 导入threading模块import Queue # 导入Queue模块class Producer(threading.Thread):# 定义生产者类def __init__(self,threadname):threading.Thread.__init__(self,name = threadname)def run(self):global queue # 声明queue为全局变量queue.put(self.getName()) # 调用put方法将线程名添加到队列中print self.getName(),'put ',self.getName(),' to queue'class Consumer(threading.Thread):# 定义消费者类def __init__(self,threadname):threading.Thread.__init__(self,name = threadname)def run(self):global queueprint self.getName(),'get ',queue.get(),'from queue'#调用get方法获取队列中内容queue = Queue.Queue() # 生成队列对象plist = []# 生成者对象列表clist = []# 消费者对象列表for i in range(10):p = Producer('Producer' + str(i))plist.append(p)# 添加到生产者对象列表for i in range(10):c = Consumer('Consumer' + str(i))clist.append(c)# 添加到消费者对象列表for i in plist:i.start() # 运行生产者线程i.join()for i in clist:i.start() # 运行消费者线程i.join()######运行结果######>>> Producer0 put Producer0 to queueProducer1 put Producer1 to queueProducer2 put Producer2 to queueProducer3 put Producer3 to queueProducer4 put Producer4 to queueProducer5 put Producer5 to queueProducer6 put Producer6 to queueProducer7 put Producer7 to queueProducer8 put Producer8 to queueProducer9 put Producer9 to queueConsumer0 get Producer0 from queueConsumer1 get Producer1 from queueConsumer2 get Producer2 from queueConsumer3 get Producer3 from queueConsumer4 get Producer4 from queueConsumer5 get Producer5 from queueConsumer6 get Producer6 from queueConsumer7 get Producer7 from queueConsumer8 get Producer8 from queueConsumer9 get Producer9 from queue
如果觉得《python:threading多线程模块-使用Queue模块保持线程同步》对你有帮助,请点赞、收藏,并留下你的观点哦!