# -*- coding: utf-8 -*-
from queue import Queue
import random,threading,time
#生产者类
class Producer(threading.Thread):
def __init__(self, name,queue): # Python的Queue模块提供一种适用于多线程编程的FIFO实现
threading.Thread.__init__(self, name=name)#name=先生产-Producer
self.data=queue ###赋值
def run(self):
for i in range(10):
print("生产者%s将产品%d加入队列!" % (self.getName(), i)) ##getName(): 返回线程名
self.data.put(i) ## queue.put(item) 写入队列 生产者负责往仓库运输商品,而消费者负责从仓库里取出商品,
time.sleep(random.random()) ###sleep 随机数
print("生产者%s完成!" % self.getName()) ## getName(): 返回线程名
#消费者类
class Consumer(threading.Thread):
def __init__(self,name,queue): # Python的Queue模块提供一种适用于多线程编程的FIFO实现
threading.Thread.__init__(self,name=name)
self.data=queue ###赋值
def run(self):
for i in range(10):
val = self.data.get() #生产者负责往仓库运输商品,而消费者负责从仓库里取出商品,
print("消费者%s将产品%d从队列中取出!" % (self.getName(),val))
time.sleep(random.random())
print("消费者%s完成!" % self.getName())
if __name__ == '__main__':
print('-----主线程开始-----')
queue = Queue() # 实例化队列
producer = Producer('先生产-Producer',queue) # 实例化线程Producer,并传入队列作为参数
consumer = Consumer('后消费-Consumer',queue) # 实例化线程Consumer,并传入队列作为参数
producer.start() # 启动线程Producer
consumer.start() # 启动线程Consumer
producer.join() # 等待线程Producer结束
consumer.join() # 等待线程Consumer结束
print('-----主线程结束-----')
python 多线程 先进先出
最新推荐文章于 2024-05-20 20:26:39 发布