标签:
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import threading
import queue
import time
class ThreadPool:
def __init__(self, maxsize=5):
self.maxsize = maxsize
self._q = queue.Queue(self.maxsize) # 创建队列,队列最大容量为5
for i in range(self.maxsize):
self._q.put(threading.Thread) # 循环5次,在队列中放入5个线程类名
def get_thread(self):
return self._q.get() # 获取队列中一个成员
def add_thread(self):
self._q.put(threading.Thread) # 在队列中增加一个成员
pool = ThreadPool() # 实例化一个线程池
def task(arg, p): # 创建一个函数,函数调用线程池的add_thread方法
print(arg)
time.sleep(1)
p.add_thread()
for i in range(100):
t = pool.get_thread() # 从队列中获取一个类名 t()表示创建这个类的对象
obj = t(target=task, args=(i, pool))
obj.start()
标签:
原文地址:http://www.cnblogs.com/terrycy/p/5909178.html