【无标题】

python实现简单的生产者,消费者

from threading import Thread, current_thread
import random
import time
from queue import Queue

queue = Queue(5)     #只能容纳5个数据


class ProducerThread(Thread):
    def run(self):
        name = current_thread().getName()  ##获取线程名字
        nums = range(100)  #获取100以内的随机数
        global queue
        while True:
            num = random.choice(nums)    #获取随机数
            queue.put(num)   #将生产的数据放入队列当中
            print('生产者 %s 生产了数据 %s' % (name, num))  #生产的数据
            t = random.randint(1, 3)       #随机的休眠时间
            time.sleep(t)  #生产者休眠
            print('生产者 %s 休眠了 %s 秒' % (name, t))


class ConsumerThread(Thread):
    def run(self):
        name = current_thread().getName() #获取消费者线程名称
        global queue
        while True:
            num = queue.get()  #从生产者提取数据
            queue.task_done()  #task_done()  封装了线程等待和同步的时间
            print('消费者 %s 消耗了数据 %s' % (name, num))
            t = random.randint(1, 5)    #随机等待
            time.sleep(t)
            print('消费者 %s 休眠了 %s 秒' % (name, t))

#以一个生产者和一个消费者为例
p1 = ProducerThread(name='p1')
p1.start()
c1 = ConsumerThread(name='c1')
c1.start()

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值