- 实现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.*;
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);
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出现问题");
}
}
}
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 【译】Visual Studio 中新的强大生产力特性
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义