1+ # encoding: utf-8
2+ __author__ = 'zhanghe'
3+
4+ from Queue import Queue
5+ import random
6+ import threading
7+ import time
8+
9+
10+ class Producer (threading .Thread ):
11+ """
12+ Producer thread
13+ """
14+ def __init__ (self , t_name , queue ):
15+ threading .Thread .__init__ (self , name = t_name )
16+ self .data = queue
17+
18+ def run (self ):
19+ for i in range (5 ):
20+ print "%s: %s is producing %d to the queue!" % (time .ctime (), self .getName (), i )
21+ self .data .put (i )
22+ time .sleep (random .randrange (10 ) / 5 )
23+ print "%s: %s finished!" % (time .ctime (), self .getName ())
24+
25+
26+ class Consumer (threading .Thread ):
27+ """
28+ Consumer thread
29+ """
30+ def __init__ (self , t_name , queue ):
31+ threading .Thread .__init__ (self , name = t_name )
32+ self .data = queue
33+
34+ def run (self ):
35+ for i in range (5 ):
36+ val = self .data .get ()
37+ print "%s: %s is consuming. %d in the queue is consumed!" % (time .ctime (), self .getName (), val )
38+ time .sleep (random .randrange (10 ))
39+ print "%s: %s finished!" % (time .ctime (), self .getName ())
40+
41+
42+ def main ():
43+ """
44+ Main thread
45+ :return:
46+ """
47+ queue = Queue ()
48+ producer = Producer ('Pro.' , queue )
49+ consumer = Consumer ('Con.' , queue )
50+ producer .start ()
51+ consumer .start ()
52+ producer .join ()
53+ consumer .join ()
54+ print 'All threads terminate!'
55+
56+
57+ if __name__ == '__main__' :
58+ main ()
59+
60+ # 本程序是比较经典的生产者和消费者模型,运行结果:
61+ # Fri Apr 24 00:05:42 2015: Pro. is producing 0 to the queue!
62+ # Fri Apr 24 00:05:42 2015: Con. is consuming. 0 in the queue is consumed!
63+ # Fri Apr 24 00:05:43 2015: Pro. is producing 1 to the queue!
64+ # Fri Apr 24 00:05:43 2015: Con. is consuming. 1 in the queue is consumed!
65+ # Fri Apr 24 00:05:44 2015: Pro. is producing 2 to the queue!
66+ # Fri Apr 24 00:05:45 2015: Pro. is producing 3 to the queue!
67+ # Fri Apr 24 00:05:46 2015: Pro. is producing 4 to the queue!
68+ # Fri Apr 24 00:05:47 2015: Pro. finished!
69+ # Fri Apr 24 00:05:51 2015: Con. is consuming. 2 in the queue is consumed!
70+ # Fri Apr 24 00:05:53 2015: Con. is consuming. 3 in the queue is consumed!
71+ # Fri Apr 24 00:05:53 2015: Con. is consuming. 4 in the queue is consumed!
72+ # Fri Apr 24 00:06:02 2015: Con. finished!
73+ # All threads terminate!
0 commit comments