多线程下载图片的方法(2种)
第一种:继承Thred方法
1、导入依赖
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.6</version>
</dependency>
2、程序
import org.apache.commons.io.FileUtils;
import java.io.File;
import java.io.IOException;
import java.net.URL;
public class TestThread1 extends Thread{
private String url;
private String name;
public TestThread1(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) {
TestThread1 testThread1 = new TestThread1("https://img.zcool.cn/community/01015260555ea311013e87f4a1d4b5.jpg@260w_195h_1c_1e_1o_100sh.jpg", "1.jpg");
TestThread1 testThread2 = new TestThread1("https://img.zcool.cn/community/019ca76054761a11013e87f43018fb.jpg@260w_195h_1c_1e_1o_100sh.jpg", "2.jpg");
TestThread1 testThread3 = new TestThread1("https://img.zcool.cn/community/016ab5605470fe11013fb11755e4ea.jpg@260w_195h_1c_1e_1o_100sh.jpg", "3.jpg");
testThread1.start();
testThread2.start();
testThread3.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错误");
}
}
}
3、控制台
注意:多线程不一定按程序写的下载顺序去执行,并且每次的顺序都不会一样
4、下载好的图片
第二种:实现Runnable接口(推荐第二种)
//创建线程方式2:实现runnablejiekou接口,重写run方法,执行线程需要丢入runnable接口的实现类,调用start
public class TestThread1 implements Runnable{
private String url;
private String name;
public TestThread1(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) {
TestThread1 testThread1 = new TestThread1("https://img.zcool.cn/community/01015260555ea311013e87f4a1d4b5.jpg@260w_195h_1c_1e_1o_100sh.jpg", "1.jpg");
TestThread1 testThread2 = new TestThread1("https://img.zcool.cn/community/019ca76054761a11013e87f43018fb.jpg@260w_195h_1c_1e_1o_100sh.jpg", "2.jpg");
TestThread1 testThread3 = new TestThread1("https://img.zcool.cn/community/016ab5605470fe11013fb11755e4ea.jpg@260w_195h_1c_1e_1o_100sh.jpg", "3.jpg");
//创建线程对象,通过线程对象来开启我们的线程,代理
// Thread thread = new Thread(testThread3);
// thread.start();
new Thread(testThread1).start();
new Thread(testThread2).start();
new Thread(testThread3).start();
// testThread1.start();
// testThread2.start();
// testThread3.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错误");
}
}