import time
import threading
import Queue
~L q#tTNU#|/R$|0
class Consumer(threading.Thread):
def __init__(self, queue):
threading.Thread.__init__(self)
self._queue = queue
51Testing软件测试网x,c'rt A1g#G*X']S7G
def run(self):
while True:
# queue.get() blocks the current thread until
# an item is retrieved.
msg = self._queue.get()
# Checks if the current message is
# the "Poison Pill"
if isinstance(msg, str) and msg == 'quit':
# if so, exists the loop
break
# "Processes" (or in our case, prints) the queue item
print "I'm a thread, and I received %s!!" % msg
# Always be friendly!
print 'Bye byes!'
C0O|3S"^0c\7O|T0
0L-~q8DX0
def Producer():
# Queue is used to share items between
# the threads.
queue = Queue.Queue()
51Testing软件测试网y-`SMU(w[
# Create an instance of the worker
worker = Consumer(queue)
# start calls the internal run() method to
# kick off the thread
worker.start()
51Testing软件测试网RR$GO8V&mC5N:@c$w0Z
# variable to keep track of when we started
start_time = time.time()
# While under 5 seconds..
while time.time() - start_time < 5:
# "Produce" a piece of work and stick it in
# the queue for the Consumer to process
queue.put('something at %s' % time.time())
# Sleep a bit just to avoid an absurd number of messages
time.sleep(1)
k*?{NR+?
p N-u$TC0
# This the "poison pill" method of killing a thread.
queue.put('quit')
# wait for the thread to close down
worker.join()
51Testing软件测试网7P'le4V4YSZ
51Testing软件测试网*[H;fk4s
du'v
if __name__ == '__main__':
Producer()
)JV^9]c#N'S6Ks#S3E8p0
-D)I{y;y1T/D5et3v9C0
http://blog.chedushi.com/archives/9158
N(hV k2_:Q3Z+q0