使用Thread类实现多线程下载图片

import java.io.File;
import java.io.IOException;
import java.net.URL;

// 利用多线程从网上下载图片
public class TestThread extends Thread {
public String url; // 网络图片地址
public String name; // 保存的文件名
@Override
public void run() {
WebDownloader webDownloader = new WebDownloader();
webDownloader.downloader(url,name);
System.out.println("下载了文件名为:" + name );
}
public TestThread(String url ,String name){
this.url = url;
this.name = name;
}
public static void main(String[] args) {
// 通过多次执行,可以发现3个线程每次执行的顺序都不同
TestThread testThread1 = new TestThread("https://t7.baidu.com/it/u=1819248061,230866778&fm=193&f=GIF","1.jpg");
TestThread testThread2 = new TestThread("https://t7.baidu.com/it/u=1819248061,230866778&fm=193&f=GIF","2.jpg");
TestThread testThread3 = new TestThread("https://t7.baidu.com/it/u=1819248061,230866778&fm=193&f=GIF","3.jpg");
testThread1.start();
testThread2.start();
testThread3.start();
}
}
// 使用commons.io类提供的FileUtils.copyURLToFile下载网络图片
class WebDownloader{
public void downloader(String url,String name){
try {
FileUtils.copyURLToFile(new URL(url),new File(name));
} catch (IOException e) {
e.printStackTrace();
System.out.println("IO异常,downloader方法出错");
}
}
}
posted @ 2021-12-27 08:51  迷路小孩  阅读(48)  评论(0)    收藏  举报