实现Runnable接口,多线程下载照片练习
代码及其注释:
package com.heima.Multithreading;
import org.apache.commons.io.FileUtils;
import java.io.File;
import java.io.IOException;
import java.net.URL;
public class TestImplementRunnable implements Runnable {
private String url;
private String name;
public TestImplementRunnable(String url, String name) {
this.url = url;
this.name = name;
}
@Override
public void run() {
WebDownLoader2 webDownLoader2 = new WebDownLoader2();
webDownLoader2.downLoad(url, name);
System.out.println("文件下载成功,文件名为" + name);
}
public static void main(String[] args) {
TestImplementRunnable t1 = new TestImplementRunnable("https://img-blog.csdn.net/20180201095756000?watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQveGlhb2ZlbmdjYW55dWVsb25n/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/SouthEast#pic_center","1.jpg");
TestImplementRunnable t2 = new TestImplementRunnable("https://img-blog.csdn.net/20180201095756000?watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQveGlhb2ZlbmdjYW55dWVsb25n/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/SouthEast#pic_center","2.jpg");
TestImplementRunnable t3 = new TestImplementRunnable("https://img-blog.csdn.net/20180201095805775?watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQveGlhb2ZlbmdjYW55dWVsb25n/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/SouthEast#pic_center","3.jpg");
new Thread(t1).start();
new Thread(t2).start();
new Thread(t3).start();
}
}
class WebDownLoader2{
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方法下载出现问题");
}
}
}