1,需要导一个jar包;commons-io-2.11.0.jar
2,编写代码
package com.xiang.lesson02;
import org.apache.commons.io.FileUtils;
import java.io.File;
import java.io.IOException;
import java.net.URL;
//练习 Thread ,实现多线程同步下载图片
public class TestThread1 extends Thread {
// 继承 Thread类;
private String url; //网络图片地址
private String name;//保存的文件名
public TestThread1(String url, String name) {
this.name = name;
this.url = url;
}
// 重写run方法
// 下载图片线程的执行体
@Override
public void run() {
WebDownloader downloader = new WebDownloader();
downloader.downloader(url,name);
System.out.println("下载了文件名:"+name);
}
public static void main(String[] args) {
TestThread1 t1 = new TestThread1("https://img-home.csdnimg.cn/images/20210907093842.jpg","t1.jpg");
TestThread1 t2 = new TestThread1("https://img-blog.csdnimg.cn/234ef937b8924d0a81271085511f6223.png","t2.jpg");
TestThread1 t3 = new TestThread1("https://img-blog.csdnimg.cn/img_convert/baf51d796db22a6a03c0ce7caf378f6f.png","t3.jpg");
// 启动线程
t1.start();
t2.start();
t3.start();
}
}
class WebDownloader {
// 下载方法
public void downloader(String url, String name) {
try {
// copyURLToFile 把网页地址,变成一个文件;
FileUtils.copyURLToFile(new URL(url), new File(name));
} catch (IOException e) {
e.printStackTrace();
System.out.println("IO异常,downloader方法出现问题");
}
}
}
3,运行结果