#!/usr/bin/env python#Encoding:utf8 fromQueueImportQueueImportRandom,threading,time#Producer ClassclassProducer (Threading. Thread):def __init__(self, name,queue): Threading. Thread.__init__(Self, name=name) Self.data=QueuedefRun (self): forIinchRange (5): Print("%s is producing%d to the queue!"%( self.getname (), i)) self.data.put (i) Time.sleep (Random.randrange (10)/5) Print("%s finished!"%self.getname ())#Consumer classclassConsumer (Threading. Thread):def __init__(self,name,queue): Threading. Thread.__init__(self,name=name) Self.data=QueuedefRun (self): forIinchRange (5): Val=Self.data.get ()Print("%s is consuming.%d of the queue is consumed!"%(Self.getname (), Val)) Time.sleep (Random.randrange (10)) Print("%s finished!"%self.getname ())defMain (): Queue=Queue () producer= Producer ('Producer', queue) consumer= Consumer ('Consumer', queue) Producer.start () Consumer.start ()#Producer.join () #Consumer.join () Print 'All Threads finished!'if __name__=='__main__': Main ()
Python implementation: Producer Consumer models (Producer Consumer model)