1. 通过重写Thread类,自定义一个get_result()方法
"""重新定义带返回值的线程类"""
from threading import Thread
from time import sleep,time
class MyThread(Thread):
def __init__(self, func, args):
super(MyThread, self).__init__()
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 sum_(a):
sleep(a)
return a*8
if __name__ =='__main__':
time1 = time()
result_list = []
#不用多线程
for i in range(1, 5):
t =sum_(i)
result_list.append(t)
for i in result_list:
print(i)
print('不用多线程耗时', time() - time1)
time2 = time()
#多线程
thread_list = []
for i in range(1,5):
t = MyThread(func=sum_,args=(i,))
t.start()
thread_list.append(t)
for i in thread_list:
t.join() # jion()方法等待线程完成
print(i.get_result())
print('多线程耗时',time()-time2)
2. 通过写入公共变量的方法
pass