python线程 发表于 2019-12-24 更新于 2020-06-30 分类于 python 获取线程执行结果 通过继承自threading.Thread,重写其run方法来实现 123456789101112131415161718192021222324252627282930313233import threadingclass MyThread(threading.Thread): def __init__(self, *args, **kwargs): """ 使用父类构造器,尽量保持语法一致,仅将线程执行结果缓存 """ #设定回调 if 'callable' in kwargs: self._callable = kwargs['callable'] del kwargs['callable'] super(MyThread, self).__init__(*args, **kwargs) self._result = None pass def run(self): if self._target: self._result = self._target(*self._args, **self._kwargs) def result(self, _callable=None): """ join()确保任务已经执行完成 :return: """ self.join() # 回调 if _callable is None: _callable = self._callable if _callable: _callable(self._result) return self._result 测试程序 12345678910111213141516import threadingimport timedef foo(): time.sleep(1) return time.time()tasks = []for i in range(10): tasks.append(MyThread(target=foo))for t in tasks: t.start()for t in tasks: t.result()