实现Callable接口(了解)
- 实现Callable接口需要返回值类型;
- 重写Call方法需要抛出异常;
- 创建目标对象;
- 执行创建服务;
- 提交执行
- 获取结果
- 关闭服务
package Demo01;
import org.apache.commons.io.FileUtils;
import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.util.concurrent.*;
public class TestCallable implements Callable<Boolean> {
private String url;
private String name;
public TestCallable(String url,String name){
this.name = name;
this.url = url;
}
@Override
public Boolean call() throws Exception {
wedDownlaoder wedDownlaoder = new wedDownlaoder();
wedDownlaoder.downloader(url,name);
System.out.println("file:"+name);
return true;
}
public static void main(String[] args) throws ExecutionException, InterruptedException {
TestCallable t1 = new TestCallable("https://img-blog.csdnimg.cn/a017ccfa420142619443e5a70250e777.png#pic_center", "t1");
TestCallable t2 = new TestCallable("https://img-blog.csdnimg.cn/698811f0becb43269562906f25a88083.png#pic_center", "t2");
TestCallable t3 = new TestCallable("https://img-blog.csdnimg.cn/4765a365ba5f43f08088ed52dc8d2208.png#pic_center", "t3");
ExecutorService ser = Executors.newFixedThreadPool(3);
Future<Boolean> r1 = ser.submit(t1);
Future<Boolean> r2 = ser.submit(t2);
Future<Boolean> r3 = ser.submit(t3);
boolean rs1 = r1.get();
boolean rs2 = r2.get();
boolean rs3 = r3.get();
ser.shutdownNow();
}
}
class wedDownlaoder{
public void downloader(String url,String name){
try {
FileUtils.copyURLToFile(new URL(url),new File(name));
} catch (IOException e) {
e.printStackTrace();
}
}
}