- 实现Callable接口,需要返回值类型
- 重写call方法,需要抛出异常
- 创建目标对象 TestCallable t1 = new TestCallable("https://i0.hdslb.com/bfs/archive/5c2bafe17dd19215a4346c047d5b2cb0c19f958c.png","1.png");
- 创建执行服务:ExecutorService s = Executors.newFixedThreadPool(1);
- 提交执行:Future r1 = s.submit(t1);
- 获取结果:boolean rg = r1.get();
- 关闭服务:s.shutdownNow();
package com.thread.callable;
import org.apache.commons.io.FileUtils;
import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.util.concurrent.*;
//线程创建方式三:实现callable接口
/**
* callable好处
*1.可以定义返回值
*2.可以抛出异常
*/
public class TestCallable implements Callable<Boolean> {
private String url; //保存网络地址
private String name; //保存的文件名
public TestCallable(String url,String name){
this.url=url;
this.name=name;
}
//下载图片的线程执行体
@Override
public Boolean call() {
WebDownloder webDownloder = new WebDownloder();
webDownloder.downloder(url,name);
System.out.println("下载了文件名为"+name);
return true;
}
public static void main(String[] args) throws ExecutionException, InterruptedException {
TestCallable t1 = new TestCallable("https://i0.hdslb.com/bfs/archive/5c2bafe17dd19215a4346c047d5b2cb0c19f958c.png","1.png");
TestCallable t2 = new TestCallable("https://i0.hdslb.com/bfs/archive/81612a622ed8b88ebda750ee14b7f9cc3431f43c.jpg@672w_378h_1c.webp","2.jpg");
TestCallable t3 = new TestCallable("https://i0.hdslb.com/bfs/archive/bc232c2e1886d965d762979d01de4cea7d738150.jpg@672w_378h_1c.webp","3.jpg");
//创建执行服务
ExecutorService executorService = Executors.newFixedThreadPool(3); //拥有3个线程的线程池
//提交执行
Future<Boolean> res1 = executorService.submit(t1);
Future<Boolean> res2 = executorService.submit(t2);
Future<Boolean> res3 = executorService.submit(t3);
//获取结果
Boolean aBoolean1 = res1.get();
Boolean aBoolean2 = res1.get();
Boolean aBoolean3 = res1.get();
System.out.println(aBoolean1);
System.out.println(aBoolean2);
System.out.println(aBoolean3);
//关闭服务
executorService.shutdownNow();
}
}
//下载器
class WebDownloder{
//下载方法
public void downloder(String url,String name){
try {
FileUtils.copyURLToFile(new URL(url),new File(name));
} catch (IOException e) {
e.printStackTrace();
System.out.println("IO异常,downloder出现问题");
}
}
}