编写代码
package com.xiang.lesson06;
import org.apache.commons.io.FileUtils;
import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.util.concurrent.*;
// 实现Callable 接口;
public class TestCallable implements Callable {
private String url; //网络图片地址
private String name;//保存的文件名
public TestCallable(String url, String name) {
this.name = name;
this.url = url;
}
@Override
public Boolean call() throws Exception {
WebDownloader downloader = new WebDownloader();
downloader.downloader(url,name);
System.out.println("下载了文件名:"+name);
return true;
}
public static void main(String[] args) throws Exception {
TestCallable t1 = new TestCallable("https://img-home.csdnimg.cn/images/20210907093842.jpg","t1.jpg");
TestCallable t2 = new TestCallable("https://img-blog.csdnimg.cn/234ef937b8924d0a81271085511f6223.png","t2.jpg");
TestCallable t3 = new TestCallable("https://img-blog.csdnimg.cn/img_convert/baf51d796db22a6a03c0ce7caf378f6f.png","t3.jpg");
//创建执行服务
ExecutorService pool = Executors.newFixedThreadPool(3);
// 提交执行
Future s1 = pool.submit(t1);
Future s2 = pool.submit(t2);
Future s3 = pool.submit(t3);
// 获取结果
Object o1 = s1.get();
Object o2 = s2.get();
Object o3 = s3.get();
// 关闭服务
pool.shutdownNow();
}
}
class WebDownloader {
// 下载方法
public void downloader(String url, String name) {
try {
// copyURLToFile 把网页地址,变成一个文件;
FileUtils.copyURLToFile(new URL(url), new File(name));
} catch (IOException e) {
e.printStackTrace();
System.out.println("IO异常,downloader方法出现问题");
}
}
}
运行结果
java多线程 Callable 接口 实现图片下载