代码
# -*- coding:utf-8 -*-
import time
import threading
"""重新定义带返回值的线程类"""
class ThreadWithReturn(threading.Thread):
def __init__(self,func,args=()):
super(ThreadWithReturn,self).__init__()
self.func = func
self.args = args
self.result = None
def run(self):
self.result = self.func(*self.args)
def get_result(self):
try:
return self.result
except Exception:
return None
def get_data(uid, name):
print("time sleep 10s ")
time.sleep(10)
return {"name":name}
def get_datas():
args_list = [
{"id":"1","name":"jon"},
{"id":"1","name":"库里"},
{"id":"1","name":"詹姆斯"},
{"id":"1","name":"威少"},
{"id":"1","name":"奥尼尔"},
{"id":"1","name":"利拉德"},
{"id":"2","name":"哈登"}
]
datas = []
threads = []
for args in args_list:
thead_i = ThreadWithReturn(func=get_data, args= (args.get("id"), args.get("name")))
threads.append(thead_i)
[n.start() for n in threads]
# join()等待方法执行完成
[n.join() for n in threads]
# n.result 获取返回值
return [n.result for n in threads]
if __name__ == "__main__":
datas = get_datas()
print(datas)
运行
[root@test tmp]# time python3 test.py
time sleep 10s
time sleep 10s
time sleep 10s
time sleep 10s
time sleep 10s
time sleep 10s
time sleep 10s
[{'name': 'jon'}, {'name': '库里'}, {'name': '詹姆斯'}, {'name': '威少'}, {'name': '奥尼尔'}, {'name': '利拉德'}, {'name': '哈登'}]
real 0m1.185s
user 0m0.059s
网友评论