import threading
import Queue
import time
import random
from faker import Faker
class MyThread(threading.Thread):
'''
线程模型
'''
def __init__(self,queue):
threading.Thread.__init__(self)
self.queue = queue
self.start()
def run(self):
while True:
try:
task = self.queue.get(block=False)
time.sleep(random.random())
print 'Task %s Done' % task
self.queue.task_done()
except Exception,e:
break
class MyThreadPool():
def __init__(self,queue,size):
self.queue = queue
self.pool = []
for i in range(size):
self.pool.append(MyThread(queue))
def joinAll(self):
for thd in self.pool:
if thd.isAlive(): thd.join()
if __name__ == '__main__':
q = Queue.Queue(10)
fake = Faker()
for i in range(5):
q.put(fake.word())
pool = MyThreadPool(queue=q,size=2)
pool.joinAll()