Callable接口
- 实现Callable接口,需要返回值类型
- 重写call方法,需要抛出异常
- 创建目标对象
- 创建执行服务
- 提交执行
- 获取结果
- 关闭服务
修改下载图片
import java.util.concurrent.*;
public class StartCallable implements Callable<Boolean> {
private String url = ""; // 网络图片地址
private String name = ""; // 保存路径
// 构造器,初始化地址
public StartCallable(String url,String name){
this.url = url;
this.name = name;
}
@Override
public Boolean call() {
WebDownloader webDownloader = new WebDownloader();
webDownloader.downloader(url, name);
System.out.println("路径"+name);
return true; // Callable多一个返回值
}
// 启动线程
public static void main(String[] args) throws ExecutionException, InterruptedException {
String url = "https://img0.bdstatic.com/static/searchdetail/img/logo-2X_2dd9a28.png";
String name = "C:\\Users\\Jie7\\IdeaProjects\\Test\\src\\baidulogo";
// 多线程,启动,无序
StartCallable picThread1 = new StartCallable(url, name +"1.png");
StartCallable picThread2 = new StartCallable(url, name +"2.png");
StartCallable picThread3 = new StartCallable(url, name +"3.png");
// 创建执行服务,三个线程
ExecutorService ser = Executors.newFixedThreadPool(3);
// 提交执行
Future<Boolean> r1 = ser.submit(picThread1);
Future<Boolean> r2 = ser.submit(picThread2);
Future<Boolean> r3 = ser.submit(picThread3);
// 可以获取返回值
// boolean re1 = r1.get();
// boolean re2 = r2.get();
// boolean re3 = r3.get();
// 关闭服务
ser.shutdown();
}
}