# run方法是线程启动之后要执行的回调方法(钩子函数) # 所以启动线程不能够直接调用run方法而是通过start方法启动线程 # 什么时候需要使用回调式编程? # 你知道要做什么但不知道什么时候会做这件事情 defrun(self): # 线程启动之后要执行的操作 pass defmain(): a1 = Account() threads=[] for _ in range(100): # time.sleep(0.1) t = AddMoneyThread(a1,1) threads.append(t) t.start() for t in threads: #等待线程执行完 t.join()
print(a1.balance)
2. 直接通过threading.Thread
1 2 3 4 5 6 7 8 9
threads = [] account = Acount() for _ in range(100): t = threading.Thread(target=add_money, args=(account, 1)) threads.append(t) t.start() for t in threads: t.join() print(account.banlnce)
#创建线程池 pool = ThreadpoolExcutor(max_workers=10) futures = [] # 调用线程池中的线程来执行特定的任务 for _ in range(100): future = pool.submit(add_money,account,1) futures.append(future) pool.shoutdown() for future in futures: future.result() print(account.banlance)
#也可以用上下文方法 futures = [] with ThreadpoolExcutor(max_workers=10) as pool: for _ in range(100): futures.append(pool.submit(add_money,account,1)) for future in futures: # 获取函数add_money的返回值 future.result()