Python 无法理解threading无法join掉线程的原因
#coding:utf-8import threading
import Queue
import time
class PoolClass(object):
'''
1、建立空的队列
2、设置可并行的线程数量
'''
def __init__(self,thread_sum=5):
self.queue=Queue.Queue()
self.thread_sum=thread_sum
self.threads_list=Queue.Queue()
'''
将任务添加到队列中
'''
def add_pool(self,task):
print "把数据放入队列: %d" % task
self.queue.put(task)
'''
取出队列任务并且启动线程
'''
def exec_pool(self,func):
while True:
# print "线程列表数量: %d" % len(self.threads)
# 判断队列是否为空,如果是空得则结束
if self.queue.empty():
if self.threads_list.empty():
print "Finish Work!"
break
else:
print "创建线程"
# 创建线程使用
for i in range(self.thread_sum):
task=self.queue.get()
thr=threading.Thread(target=func,args=(task,))
self.threads_list.put(thr)
thr.start()
print "join线程"
while self.threads_list.empty():
print "把线程读取出来"
th=self.threads_list.get()
if th.isAlive():
print "然后JOIN掉"
th.join()
# for item in self.threads_list:
# # print item
# # print item.isAlive()
# if not item.isAlive():
# print "AAAAAAA"
# if item.join():
# print "join ok!"
# # if item.is_alive():
# # item.join()
# # self.threads_list.remove(item)
# # else:
# # continue
def jobtest(n):
print "正在执行任务中:%d" % n
if __name__=='__main__':
t=PoolClass()
for i in range(20):
t.add_pool(i)
t.exec_pool(jobtest)
页:
[1]