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)