ThreadPoolExecutor实现异步多线程

import time
from concurrent.futures import ThreadPoolExecutor
executor = ThreadPoolExecutor(max_workers=20)

list = []

#  子线程要执行的函数,一般这里的函数比较耗时,所以要用异步。列表要把线程完成的标志加入到全局列表中。
def a(c):
    time.sleep(c)
    print('我是一个线程')
    list.append('1')

#  启动20个线程,注意这里,实现了异步,启动线程后,主线程继续往下运行
for x in range(20):
    #  这里,a()的参数传递方式如下
    executor.submit(a,(5))

print('我是主线程')
#  通过查看列表中元素个数来判定线程完成情况
while True:
    if len(list)== 20:
        break
print('ok')

猜你喜欢

转载自www.cnblogs.com/chaojiyingxiong/p/10748723.html