python多线程实战案例
时间: 2024-02-03 09:10:34 浏览: 108
当然可以!以下是一个简单的Python多线程实战案例:
案例:下载图片
```python
import threading
import requests
def download_image(url, filename):
response = requests.get(url)
with open(filename, 'wb') as f:
f.write(response.content)
print(f"Downloaded {filename}")
# 图片链接列表
image_urls = [
"https://example.com/image1.jpg",
"https://example.com/image2.jpg",
"https://example.com/image3.jpg",
"https://example.com/image4.jpg",
"https://example.com/image5.jpg"
]
# 创建线程列表
threads = []
for i, url in enumerate(image_urls):
filename = f"image{i+1}.jpg"
# 创建线程并启动
t = threading.Thread(target=download_image, args=(url, filename))
t.start()
threads.append(t)
# 等待所有线程完成
for t in threads:
t.join()
print("All images downloaded")
```
在这个案例中,我们使用了多线程来同时下载多张图片。每个线程负责下载一张图片,通过传入不同的图片链接和文件名来区分不同的线程。通过创建并启动多个线程,我们可以同时下载多张图片,提高下载效率。
阅读全文