创建一个Thread的实例,并传给它一个可调用的类对象
import threading from time import sleep from datetime import datetimeclass ThreadFunc: def init(self, func, args, name=''): self.name = name self.func = func self.args = args
def call(self): #调用类内的方法 print('******************') print('param:---->' + self.name) #完成之后可以调用传入的方法 self.func(self.args) def get_date_str(dt): return datetime.strftime(dt, '%Y-%m-%d %H-%M-%S') def subthread(thid, sec): print(f'subthread-线程{thid},Start at {get_date_str(datetime.now())} ,sleep{sec} s') sleep(sec) print(f'subthread-线程{thid},End at {get_date_str(datetime.now())} ,sleep{sec} s') def main(): print('-' 10 + 'ALL START:' + get_date_str(datetime.now()) + '-' 10) threads = [] loops = [4, 2] thread_count = range(len(loops)) for i in thread_count: threads.append(threading.Thread(target=ThreadFunc(subthread, (i, loops[i]),subthread.name)))
for i in thread_count: threads[i].start() for i in thread_count: threads[i].join() # 线程全部结束之后主线程才会退出 print('-' 10 + 'ALL End:' + get_date_str(datetime.now()) + '-' 10)
if name == 'main': main()
评论