zoukankan      html  css  js  c++  java
  • 生产者-消费者模型(自定义类 与函数 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()
  • 相关阅读:
    数据库的三大范式
    mysql中变量的定义
    java实现用两个栈实现队列
    java实现替换空格
    java实现二维数组中查找
    struts2核心配置之Action
    struts2核心配置之struts.xml
    初识struts2
    $.ajax()参数详解
    百度Map-JSAPI-覆盖物范围查询标记
  • 原文地址:https://www.cnblogs.com/fengjian2016/p/5259023.html
Copyright © 2011-2022 走看看