1 Star 0 Fork 147

夏国秦/geekbangpython

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
该仓库未声明开源许可证文件(LICENSE),使用请关注具体项目描述及其代码上游依赖。
克隆/下载
con_cus.py 1.10 KB
一键复制 编辑 原始数据 按行查看 历史
wilson_yin 提交于 2018-05-28 16:33 +08:00 . exercise & timegeekbang.com
from threading import Thread,current_thread
import time
import random
from queue import Queue
queue = Queue(5)
class ProducerThread(Thread):
def run(self):
name = current_thread().getName()
nums = range(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 ConsumerTheard(Thread):
def run(self):
name = current_thread().getName()
global queue
while True:
num = queue.get()
queue.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()
p2 = ProducerThread(name = 'p2')
p2.start()
p3 = ProducerThread(name = 'p3')
p3.start()
c1 = ConsumerTheard(name = 'c1')
c1.start()
c2 = ConsumerTheard(name = 'c2')
c2.start()
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
1
https://gitee.com/guoqinx/geekbangpython.git
git@gitee.com:guoqinx/geekbangpython.git
guoqinx
geekbangpython
geekbangpython
master

搜索帮助