一般线程的使用:

参考; https://www.runoob.com/python3/python3-multithreading.html

 

带返回值

#encoding=utf-8
'''
@time 2019-10-11
@author: sea
'''
import threading

print("#######################################################")
print("########## ThreadUtils 执行多个线程,并返回结果           ############")
print("#######################################################")

class ThreadUtils(threading.Thread):
    def __init__(self, func, args, name=''):
        threading.Thread.__init__(self)
        self.name = name
        self.func = func
        self.args = args
        self.result = self.func(*self.args)
 
    def get_result(self):
        try:
            return self.result
        except Exception:
            return None
#--------------------------------------------------------------
 
def method1(name):
    print("方法一执行了  "+name)
    return "你好吗?"


def method2(name):
    print("方法2 执行了  "+name)
    return "还可以"
 
 
 
 
def main():
    threads = []
    t = ThreadUtils(method1, ("线程1",))
    threads.append(t)
    
    t2 = ThreadUtils(method2, ("线程2",))
    threads.append(t2)
        
        
    for i in range(len(threads)):   # start threads 此处并不会执行线程,而是将任务分发到每个线程,同步线程。等同步完成后再开始执行start方法
        threads[i].start()
    for i in range(len(threads)):   # jion()方法等待线程完成
        threads[i].join()
    print(threads[1].get_result())
    print(threads[0].get_result())
 
 
if __name__ == '__main__':
    main()

 

posted on 2019-10-11 15:24  lshan  阅读(1052)  评论(1编辑  收藏  举报