引入pom
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.6</version>
</dependency>
代码
package xiong.demo1;
import org.apache.commons.io.FileUtils;
import java.io.File;
import java.io.IOException;
import java.net.URL;
public class TestThread2Download implements Runnable {
private String url;
private String name;
public TestThread2Download(String url,String name){
this.url = url;
this.name = name;
}
public void run(){
//下载图片
TestThread2Download.WebDownloader webDownloader = new TestThread2Download.WebDownloader();
webDownloader.downloader(url,name);
System.out.println("下载了图片-->"+name);
}
public static void main(String[] args){
TestThread2Download t1 = new TestThread2Download("https://img-blog.csdnimg.cn/af0781733ad348d28d2d0d17bbcb8c2b.png","你好1.jpg");
TestThread2Download t2 = new TestThread2Download("https://img-blog.csdnimg.cn/4063a22e5f114452a655a1c6bd787018.png","你好2.jpg");
TestThread2Download t3 = new TestThread2Download("https://img-blog.csdnimg.cn/ced787d7ecff421d90d7c7ecdaa8472f.png","你好3.jpg");
new Thread(t1).start();
System.out.println("执行了t1");
new Thread(t2).start();
System.out.println("执行了t2");
new Thread(t3).start();
System.out.println("执行了t3");
}
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("downloader方法出现异常");
}
}
}
}
运行结果