练习继承Thread,实现多线程同步下载图片
代码加上详细注释
package com.heima.Multithreading;
import org.apache.commons.io.FileUtils;
import java.io.File;
import java.io.IOException;
import java.net.URL;
//练习继承Thread,实现多线程同步下载图片
public class TestExtendThread extends Thread{
private String url;//图片地址
private String name;//保存的文件名
//手写构造器
public TestExtendThread(String url,String name){
this.url = url;
this.name = name;
}
//下载图片的线程执行体
@Override
public void run() {
//创建一个线程对象
WebDownLoader webDownLoader = new WebDownLoader();
//调用start开启线程
webDownLoader.downLoad(url,name);
System.out.println("文件下载成功,文件名为"+name);
}
//main主线程
public static void main(String[] args) {
TestExtendThread t1 = new TestExtendThread("https://img-blog.csdn.net/20180201095756000?watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQveGlhb2ZlbmdjYW55dWVsb25n/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/SouthEast#pic_center","1.jpg");
TestExtendThread t2 = new TestExtendThread("https://img-blog.csdn.net/20180201095756000?watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQveGlhb2ZlbmdjYW55dWVsb25n/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/SouthEast#pic_center","2.jpg");
TestExtendThread t3 = new TestExtendThread("https://img-blog.csdn.net/20180201095805775?watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQveGlhb2ZlbmdjYW55dWVsb25n/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/SouthEast#pic_center","3.jpg");
t1.start();
t2.start();
t3.start();
}
}
//下载器
class WebDownLoader{
//下载方法
public void downLoad(String url,String name){
try {
FileUtils.copyURLToFile(new URL(url),new File(name));
} catch (IOException e) {
e.printStackTrace();
System.out.println("IO异常,downLoad方法下载出现问题");
}
}
}
结果展示
证明了是多线程同步进行,小的照片就先下载好了