1 from threading import Thread
2
3
4 class MyThread(Thread):
5 def __init__(self, func, *params, **kwargs):
6 """
7 :param func: object 待执行的函数对象
8 :param params: tuple 函数的参数
9 :param kwargs: dict 函数的key-value参数
10 """
11 Thread.__init__(self)
12 self.func = func
13 self.args = params
14 self.kwargs = kwargs
15 self.result = None
16
17 # 调用MyThread.start()时该函数会自动执行
18 def run(self):
19 self.result = self.func(*self.args, **self.kwargs)
20
21
22 class Threads(object):
23 """
24 并发执行多个线程,并获取进程的返回值
25 """
26 def __init__(self):
27 self.threads = list()
28 self.result = list() # 进程执行的返回值组成的列表
29
30 def add(self, my_thread):
31 """
32 将任务添加到待执行线程队列中
33 :param my_thread: MyThread 线程对象
34 :return:
35 """
36 self.threads.append(my_thread)
37
38 def exec(self):
39 """
40 多线程同时执行线程队列中的人物
41 :return:
42 """
43 # 启动进程序列
44 for t in self.threads:
45 t.start()
46
47 # 等待进程序列执行完成
48 for t in self.threads:
49 t.join()
50
51 # 获取线程返回值
52 for t in self.threads:
53 self.result.append(t.result)
54
55
56 if __name__ == "__main__":
57 from time import sleep
58
59 def test_add(name, a, b, num):
60 for i in range(num):
61 sleep(1)
62 print("{}: {}".format(name, i))
63 return a+b
64
65 thread1 = MyThread(test_add, "thread1", 1, 2, 5)
66 thread2 = MyThread(test_add, "thread2", a=2, b=3, num=4)
67 threads = Threads()
68 threads.add(thread1)
69 threads.add(thread2)
70 threads.exec()
71 print(threads.result)