#coding = utf-8 ''' ''' # 生产者消费者案例 import time import threading import random # 设定共享区 count = 0 # 获取条件变量对象 condition = threading.Condition() # 定义生产者线程 class Producer(threading.Thread): # 构造方法 def __init__(self,pname): threading.Thread.__init__(self) self.pname = pname def run(self): global count while True: # 锁定共享区 if condition.acquire(): # 判断共享区书否已满 if count >= 10: print("【信息】共享区已满,生产者进入阻塞状态,请消费...") #生产者线程等待 condition.wait() else: #向共享区添加数据 count += 1 print("[{0}]给共享区添加了数据1,当前共享区数据为{1}".format(self.pname,count)) # 唤醒消费者线程 condition.notify() # 释放锁定 condition.release() # 休眠 time.sleep(random.randint(1,5)) pass class Customer(threading.Thread): # 构造方法 def __init__(self, cname): threading.Thread.__init__(self) self.cname = cname #覆盖run放法 def run(self): global count while True: if condition.acquire(): if count < 1: print("【信息】共享区已空,消费者进入阻塞状态,请生产...") condition.wait() else: count -= 1 print("[{0}]消费了数据1,当前共享区数据为{1}".format(self.cname,count)) #唤醒生产者线程 condition.notify() condition.release() time.sleep(random.randint(1,5)) pass if __name__ == '__main__': for i in range(3): p = Producer("生产者{0}".format(i + 1)) p.start() for i in range(3): c = Customer("消费者{0}".format(i + 1)) c.start() pass