环境
- Python3.2+
- 标准库concurrent.futures模块
线程池
from concurrent.futures import ThreadPoolExecutor
进程池
from concurrent.futures import ProcessPoolExecutor
代码示例
from time import sleep, time
from threading import current_thread
from concurrent.futures import ThreadPoolExecutor
thread_name = lambda: current_thread().getName()
def work(num):
print("正在下载", num, "当前线程:", thread_name())
sleep(1)
print("下载完成", num, "当前线程:", thread_name())
def multi_thread():
with ThreadPoolExecutor(max_workers=3) as thread_pool:
for num in range(3):
thread_pool.submit(work, num)
def main():
multi_thread()
if __name__ == '__main__':
t1 = time()
main()
print("耗时:", time() - t1)
执行结果
![在这里插入图片描述](https://img-blog.csdnimg.cn/20210328131136778.png)