实例(Python 2.0+)
#!/usr/bin/python# -*- coding: UTF-8 -*-importQueueimportthreadingimporttimeexitFlag = 0classmyThread(threading.Thread): def__init__(self, threadID, name, q): threading.Thread.__init__(self) self.threadID = threadID self.name = name self.q = q defrun(self): print"Starting " + self.name process_data(self.name, self.q) print"Exiting " + self.namedefprocess_data(threadName, q): whilenotexitFlag: queueLock.acquire() ifnotworkQueue.empty(): data = q.get() queueLock.release() print"%s processing %s" % (threadName, data) else: queueLock.release() time.sleep(1)threadList = ["Thread-1", "Thread-2", "Thread-3"]nameList = ["One", "Two", "Three", "Four", "Five"]queueLock = threading.Lock()workQueue = Queue.Queue(10)threads = []threadID = 1# 创建新线程fortNameinthreadList: thread = myThread(threadID, tName, workQueue) thread.start() threads.append(thread) threadID += 1# 填充队列queueLock.acquire()forwordinnameList: workQueue.put(word)queueLock.release()# 等待队列清空whilenotworkQueue.empty(): pass# 通知线程是时候退出exitFlag = 1# 等待所有线程完成fortinthreads: t.join()print"Exiting Main Thread"
以上程序执行结果:
StartingThread-1
StartingThread-2
StartingThread-3
Thread-1 processing One
Thread-2 processing Two
Thread-3 processing Three
Thread-1 processing Four
Thread-2 processing Five
ExitingThread-3
ExitingThread-1
ExitingThread-2
ExitingMainThread