Python多线程获取返回值
import threading, time
class MyThread(threading.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):
threading.Thread.join(self)
try:
return self.result
except Exception:
return None
def run1(num):
lit1 = []
for i in range(1, 6):
time.sleep(1)
i += num
lit1.append(i)
return lit1
def run2(num):
lit2 = []
for i in range(6, 11):
time.sleep(2)
i += num
lit2.append(i)
return lit2
start_time = time.time()
def test(num):
t1=MyThread(run1, (num,))
t2=MyThread(run2, (num,))
t1.start()
t2.start()
return t1.get_result(),t2.get_result()
print(test(1))
end_time = time.time()
print(end_time-start_time)