python多线程例子2

#!/usr/bin/env python
#coding=utf-8
import thread
import time
import threading
class Item:
    def __init__(self):
        self.count=0
    def add(self,n=1):
        self.count+=n
    def minus(self,n=1):
        if self.count>=n:
            self.count-=n
    def cnt(self):
        return self.count
    def isEmpty(self):
        return not self.cnt()           
class Producer(threading.Thread):
    def __init__(self,condition,item,sleeptime=1):
        threading.Thread.__init__(self)
        self.cond=condition
        self.item=item
        self.sleeptime=sleeptime        
    def run(self):
        while 1:#for i in range(5)限量..
            self.cond.acquire()
            print 'producer add item,now item cnt is',self.item.cnt()+1
            self.item.add()
            self.cond.notifyAll()
            self.cond.release()
            time.sleep(self.sleeptime)           
class Customer(threading.Thread):
    def __init__(self,name,condition,item,sleeptime=1):
        threading.Thread.__init__(self)
        self.name=name
        self.cond=condition
        self.item=item
        self.sleeptime=sleeptime
    def run(self):
        while 1:
            time.sleep(self.sleeptime)
            self.cond.acquire()
            while self.item.isEmpty():#当self.cont被notify后,还需要判断次item是否为empty,所以用while
                print self.name,'find isEmpty,so he wait..'
                self.cond.wait()
            print self.name,'get item,now item cnt is',self.item.cnt()-1
            self.item.minus()
            self.cond.release()
      def test():
    item=Item()
    condition=threading.Condition()#线程条件
    pro=Producer(condition,item,5)
    cus1=Customer('cus1',condition,item)
    cus2=Customer('cus2',condition,item)
    pro.start()
    cus1.start()
    cus2.start()
    #保持主线程运行..也是用pro.join()...使支线程加入到主线程
    while 1:
        pass
if __name__=="__main__":
    test()

你可能感兴趣的:(多线程,python)