实现callable接口-多线程下载图片
实现callable接口-多线程下载图片
说是了解即可,但在项目中还是遇到了,要掌握
实现步骤
- 实现Callable接口
- 重写call方法
- 创建目标对象 Xxxxx t1 = new Xxxxxx();
- 创建执行任务 ExecutorService ser = Executors.newFixedThreadPool(1);
- 提交执行 Future
result1 = ser.submit(t1); - 获取结果: boolean r1 = result1.get()
- 关闭服务:ser.shutdownNow()
代码
package com.example.multi_thread;
import org.apache.commons.io.FileUtils;
import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
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() throws Exception {
WebDownloader1 webDownloader1 = new WebDownloader1();
webDownloader1.download(url, name);
return true;
}
public static void main(String[] args) throws ExecutionException, InterruptedException {
TestCallable t1 = new TestCallable("https://www.baidu.com/img/PCtm_d9c8750bed0b3c7d089fa7d55720d6cf.png", "D:\\old_drive_F\\项目\\2021\\demo_kunag\\src\\main\\java\\com\\example\\multi_thread\\1.jpg");
TestCallable t2 = new TestCallable("https://www.baidu.com/img/PCtm_d9c8750bed0b3c7d089fa7d55720d6cf.png", "D:\\old_drive_F\\项目\\2021\\demo_kunag\\src\\main\\java\\com\\example\\multi_thread\\2.jpg");
TestCallable t3 = new TestCallable("https://www.baidu.com/img/PCtm_d9c8750bed0b3c7d089fa7d55720d6cf.png", "D:\\old_drive_F\\项目\\2021\\demo_kunag\\src\\main\\java\\com\\example\\multi_thread\\3.jpg");
//1. 创建执行任务
ExecutorService ser = Executors.newFixedThreadPool(3);
//2. 提交执行
Future<Boolean> result1 = ser.submit(t1);
Future<Boolean> result2 = ser.submit(t2);
Future<Boolean> result3 = ser.submit(t3);
//3. 获取结果:
boolean r1 = result1.get();
boolean r2 = result2.get();
boolean r3 = result3.get();
//4. 关闭服务:
ser.shutdownNow();
System.out.println(r1);
System.out.println(r2);
System.out.println(r3);
}
}
class WebDownloader1 {
public void download(String url, String name) throws IOException {
FileUtils.copyURLToFile(new URL(url), new File(name));
}
}
结果
true
true
true