#!/usr/bin/env python# -*- coding: utf-8 -*- from threading import Threadfrom Queue import Queueimport time class Producer(Thread): def __init__(self,name,queue): self.__name = name self.__queue = queue super(Producer,self).__init__() def run(self): while 1: if self.__queue.full(): time.sleep(1) else: self.__queue.put(‘bread‘) time.sleep(1) print ‘%s produce a bread‘ %(self.__name,) class Consumer(Thread): def __init__(self,name,queue): self.__name = name self.__queue = queue super(Consumer,self).__init__() def run(self): while 1: if self.__queue.empty(): time.sleep(1) else: self.__queue.get() time.sleep(1) print ‘%s eat a bread‘ % (self.__name,) que = Queue(maxsize=100) for p in range(3): name = ‘P%d‘ % (p,) temp = Producer(name, que) temp.start() for item in range(20): name = ‘C%d‘ % (item,) temp = Consumer(name, que) temp.start()
时间: 2024-11-02 08:41:20