生产者-消费者模型(自定义类 与函数 2种实现方式)

#!/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()

 

posted @ 2016-03-09 17:37  fengjian1585  阅读(235)  评论(0编辑  收藏  举报