功能封装
import threading
class MyThread(threading.Thread):
def __init__(self, func, args, name=''):
threading.Thread.__init__(self)
self.name = name
self.func = func
self.args = args
def run(self):
self.result = self.func(*self.args)
def get_result(self):
try:
return self.result
except Exception:
return None
执行:
def main():
threads = []
nloops = 函数列表
for i in nloops:
t = MyThread(函数, (参数,))
threads.append(t)
for i in threads : # start threads 此处并不会执行线程,而是将任务分发到每个线程,同步线程。等同步完成后再开始执行start方法
i.start()
results= []
for i in threads: # jion()方法等待线程完成
i.join()
results.append(i.get_result()) # 获取所有结果列表
print(threads[1].get_result()) # 获取其中一个结果