package com.Test;
import org.apache.commons.io.FileUtils;
import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.util.concurrent.*;
//开启线程方式三:实现Callable接口
//实现Callable的好处
//可以抛出异常
//可以获取返回值
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() {
WebDownLoader webDownLoader = new WebDownLoader();
webDownLoader.downloader(url,name);
System.out.println("下载了"+name);
return true;
}
public static void main(String[] args) throws ExecutionException, InterruptedException {
TestCallable thread1 = new TestCallable("https://www.kuangstudy.com/assert/course/c1/04.jpg","4.jpg");
TestCallable thread2 = new TestCallable("https://www.kuangstudy.com/assert/course/c1/05.jpg","5.jpg");
TestCallable thread3 = new TestCallable("https://www.kuangstudy.com/assert/course/c1/06.jpg","6.jpg");
// 创建执行服务
ExecutorService ser = Executors.newFixedThreadPool(3);
// 提交执行
Future<Boolean> r1 = ser.submit(thread1);
Future<Boolean> r2 = ser.submit(thread2);
Future<Boolean> r3 = ser.submit(thread3);
// 获取结果
boolean rs1 = r1.get();
boolean rs2 = r2.get();
boolean rs3 = r3.get();
// 关闭服务
ser.shutdownNow();
}
// 下载器
class WebDownLoader{
//下载方法
public void downloader(String url,String name){
try {
FileUtils.copyURLToFile(new URL(url), new File(name));
} catch (IOException e) {
e.printStackTrace();
System.out.println("下载器有问题,downloader方法有bug");
}
}
}
}
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 25岁的心里话
· 闲置电脑爆改个人服务器(超详细) #公网映射 #Vmware虚拟网络编辑器
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· 零经验选手,Compose 一天开发一款小游戏!
· 通过 API 将Deepseek响应流式内容输出到前端