思路:
1.psvm中希望写的代码:
TestThread testThread = new TestThread(url,name);
2.由于要网类TestThread中传参,则要重写TestThread的构造方法
3.然后着手与重写run()方法,run方法会在线程初始化时默认调用,run方法中放入关键性方法
4.另外写一个WebDownloader类,在run方法中将其实例化并调用其方法。
package thread.multithreading_download_src;
import org.apache.commons.io.FileUtils;
import java.io.File;
import java.io.IOException;
import java.net.URL;
public class TestThread extends Thread {
//写个构造方法
private String url;
private String name;
public TestThread(String url, String name) {
this.url = url;
this.name = name;
}
//run方法线程体
@Override
public void run() {
WebDownloader webDownloader = new WebDownloader();
webDownloader.downloader(url, name);
System.out.println("Name of the downloaded file is : " + name);
}
//main主线程
public static void main(String[] args) {
TestThread t1 = new TestThread("https://tva1.sinaimg.cn/large/a7cabc30gy1fgn6y7ps99j20rs13aqbi.jpg", "pixiv_num1.jpg");
TestThread t2 = new TestThread("https://tva2.sinaimg.cn/large/a7cabc30gy1fgn6y7kdd8j20rs13a4do.jpg", "pixiv_num2.jpg");
TestThread t3 = new TestThread(("https://tva1.sinaimg.cn/large/a7cabc30gy1fgn6y7nxl2j20p00z3nae.jpg"), "pixiv_num3.jpg");
//线程的开启顺序与下载完成的顺序不一定一一对应
t1.start();
t2.start();
t3.start();
}
}
//创建下载器类
class WebDownloader{
public void downloader(String url, String name) {
try {
//实际上只有如下方法是jar包为我们写好的
//其他时候我们都只是在打包封装自己的类、方法。
FileUtils.copyURLToFile(new URL(url), new File(name));
} catch (IOException e) {
e.printStackTrace();
System.out.println("IO exception, Method downloader raised a problem");
}
}
}