#!/usr/bin/env python # -*- coding:utf-8 -*- from threading import Thread import time from Queue import Queue import random class Producer(Thread): def __init__(self,name,que): super(Producer,self).__init__() self.name = name self.que = que def run(self): while True: if self.que.qsize < 3: self.que.put('一个包子') print '生产了一个包子' else: print '队列里的包子大于3' time.sleep(random.randrange(5)) class Consumer(Thread): def __init__(self,name,que): super(Consumer,self).__init__() self.name = name self.que = que def run(self): while True: try: self.que.get_nowait() print '消费了一个包子' except Exception: print '没有包子了' time.sleep(random.randrange(2)) que = Queue() for i in range(2): name = "生产者%d"%i p1 = Producer(name,que) p1.start() for i in range(3): name = "消费者%d"%i c1 = Consumer(name,que) c1.start()
#!/usr/bin/env python # -*- coding:utf-8 -*- from threading import Thread import time from Queue import Queue import random def Producer(name,que): while True: if que.qsize < 3: que.put('一个包子') print '生产了一个包子' else: print '队列里的包子大于3' time.sleep(random.randrange(2)) def Consumer(name,que): while True: try: que.get_nowait() print '消费了一个包子' except Exception: print '没有包子了' time.sleep(random.randrange(2)) que = Queue() for i in range(10): name = "生产者%d"%i p1 = Thread(target=Producer,args=(name,que)) p1.start() for i in range(3): name = "消费者%d"%i c1 = Thread(target=Consumer,args=(name,que)) c1.start()