-
下载commons-io-2.10.0.jar并导入到包下面创建的lib(自己创建)中,导入不可以直接用,接着再右键打开lib,点击Add-as-Library添加到库里面
-
先写一个下载器,接着用FileUtils工具类中的copyURLToFile方法,将一个URL地址保存为一个文件名。
-
然后就是继承Thread类,重写run方法,调用start开启进程
package com.test;
import org.apache.commons.io.FileUtils;
import java.io.File;
import java.io.IOException;
import java.net.URL;
/**
* @author Wzjz
* @create 2021-06-15-21:53
*/
//练习Thread,实现多线程同步下载图片
public class TestThread01 extends Thread{
private String url;//网络图片地址
private String name;//保存的文件名
public TestThread01(String url , String name){//构造器
this.url = url;
this.name = name;
}
//下载图片线程的执行体
@Override
public void run() {
WebDownloader webDownloader = new WebDownloader();
webDownloader.downloader(url,name);
System.out.println("下载了文件名为:" + name);
}
public static void main(String[] args) {
TestThread01 testThread01 = new TestThread01("https://tpc.googlesyndication.com/simgad/3727760314875770166","1.jpg");
TestThread01 testThread011 = new TestThread01("https://img-blog.csdnimg.cn/20210614233633951.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3dlaXhpbl80NTAzMjMyOA==,size_16,color_FFFFFF,t_70","2.jpg");
TestThread01 testThread012 = new TestThread01("https://img-blog.csdnimg.cn/20210614233641877.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3dlaXhpbl80NTAzMjMyOA==,size_16,color_FFFFFF,t_70","3.jpg");
//线程是同时执行的,不分先后
testThread01.start();
testThread011.start();
testThread012.start();
}
}
//下载器
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方法出现问题");
}
}
}