多线程是一个可以提高程序运行效率的方法。一些按顺序执行的程序可以使用多线程实现并行执行,从而提高整体效率。
想要了解更多关于多线程的知识请点击:多线程
实例
简单使用
import time
from concurrent.futures import ThreadPoolExecutor
def new_sleep(name):
print(f'任务{name}休眠开始')
time.sleep(5)
print(f'任务{name}休眠完成')
def main():
with ThreadPoolExecutor(max_workers=2) as pool:
for i in range(1, 4):
pool.submit(new_sleep, i)
if __name__ == '__main__':
start = time.time()
main()
end = time.time()
print(f'用时:{end - start}')
360图片下载
import requests
import time
import json
from concurrent.futures import ThreadPoolExecutor
def download_img(href, num):
resp = requests.get(href)
with open(f'img/{num}.jpg', 'wb') as file:
file.write(resp.content)
def main():
count = 0
for i in range(0, 90, 30):
url = f'https://image.so.com/zjl?ch=wallpaper&sn={i}'
resp = requests.get(url)
data = json.loads(resp.text)
with ThreadPoolExecutor(max_workers=16) as pool:
for j in data['list']:
count += 1
pool.submit(download_img, j['imgurl'], count)
if __name__ == '__main__':
start = time.time()
main()
end = time.time()
print(f'用时:{end - start}')
|