Runnable接口实现多线程
package cn.usts.edu.lesson01;
import org.apache.commons.io.FileUtils;
import java.io.File;
import java.io.IOException;
import java.net.URL;
/**
* Runnable接口实现多线程
* 推荐使用Runnable接口,因为继承Thread的话一个类只能继承一个类
* thread的底层就是实现了Runnable接口【class Thread implements Runnable 】
* */
public class RunnableDemo implements Runnable {
String file;
String url;
String filename;
public RunnableDemo(String file, String url) {
this.file = file;
this.url = url;
}
@Override
public void run() {
ImageDownload2 imageDownload = new ImageDownload2();
imageDownload.downLoad(url,file);
filename = file.split("\\\\")[11];//获取文件名
System.out.println(filename+"下载完成");
}
public static void main(String[] args) {
RunnableDemo t1 = new RunnableDemo(
"D:\\all_projects\\java_projects\\java_ij\\springMVC\\ThreadStudy\\src\\cn\\usts\\edu\\lesson01\\a.jpg"
,"https://bbs.qn.img-space.com/202110/18/1c3eb5a6f1d59adaa9b608c7da64d95a.jpg");
RunnableDemo t2 = new RunnableDemo(
"D:\\all_projects\\java_projects\\java_ij\\springMVC\\ThreadStudy\\src\\cn\\usts\\edu\\lesson01\\b.jpg"
,"https://bbs.qn.img-space.com/202110/18/6d254e56adf9094cc003c815d3d6d3e1.jpg");
RunnableDemo t3 = new RunnableDemo(
"D:\\all_projects\\java_projects\\java_ij\\springMVC\\ThreadStudy\\src\\cn\\usts\\edu\\lesson01\\c.jpg"
,"https://bbs.qn.img-space.com/202110/18/72d862d6074bb2edc1e6df61ce78455f.jpg"
);
// 新建线程
new Thread(t1).start();
new Thread(t2).start();
new Thread(t3).start();
}
}
class ImageDownload2 {
public void downLoad(String url,String file) {
try {
FileUtils.copyURLToFile(new URL(url),new File(file));
} catch (IOException e) {
e.printStackTrace();
System.out.println("downLoad()方法出错");
}
}
}