代码拉取完成,页面将自动刷新
#!/usr/bin/python3
# coding: utf-8
"""
__title__ = ""
__author__ = "Hans"
__mtime__ = "2017/4/5 0005"
# code is far away from bugs with the god animal protecting
I love animals. They taste delicious.
┏┓ ┏┓
┏┛┻━━━┛┻┓
┃ ☃ ┃
┃ ┳┛ ┗┳ ┃
┃ ┻ ┃
┗━┓ ┏━┛
┃ ┗━━━┓
┃ 神兽保佑 ┣┓
┃ 永无BUG! ┏┛
┗┓┓┏━┳┓┏┛
┃┫┫ ┃┫┫
┗┻┛ ┗┻┛
"""
import random, threading, time
from queue import Queue
# producer thread
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(10): # 随机产生10个数字, 可以修改为任意大小
randomnum = random.randint(1, 99)
print('{}:{} is producing {} to the queue'.format(time.ctime(), self.getName(), randomnum))
self.data.put(randomnum) # 将数据依次存入队列
time.sleep(1)
print('{}:{} is finished!'.format(time.ctime(), self.getName()))
# Consumer thread
class Consumer_even(threading.Thread):
def __init__(self, t_name, queue):
threading.Thread.__init__(self, name=t_name)
self.data = queue
def run(self):
while 1:
try:
val_even = self.data.get(1, 5) # get(self, block=True, timeout=None) 1是阻塞等待, 5 是超时5秒
if val_even % 2 == 0:
print('{}:{} is consuming, {} in the queue is consumed'.format(time.ctime(), self.getName(), val_even))
time.sleep(2)
else:
self.data.put(val_even)
time.sleep(2)
except: # 等待输入, 超过5秒, 就报异常
print('{}:{} finished'.format(time.ctime(), self.getName()))
break
class Consumer_odd(threading.Thread):
def __init__(self, t_name, queue):
threading.Thread.__init__(self, name=t_name)
self.data = queue
def run(self):
while 1:
try:
val_odd = self.data.get(1, 5) # get(self, block=True, timeout=None) 1是阻塞等待, 5 是超时5秒
if val_odd % 2 != 0:
print('{}:{} is consuming, {} in the queue is consumed'.format(time.ctime(), self.getName(), val_odd))
time.sleep(2)
else:
self.data.put(val_odd)
time.sleep(2)
except: # 等待输入, 超过5秒, 就报异常
print('{}:{} finished'.format(time.ctime(), self.getName()))
break
# main thread
def main():
queue = Queue()
producer = Producer('Pro.', queue)
consumer_even = Consumer_even('Con_even.', queue)
consumer_odd = Consumer_odd('Con_odd', queue)
producer.start()
consumer_even.start()
consumer_odd.start()
producer.join()
consumer_even.join()
consumer_odd.join()
print('All threads terminate!')
if __name__ == "__main__":
main()
此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。
如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。