【多线程】线程创建方式三:实现callable接口

线程创建方式三:实现callable接口

代码示例:

import org.apache.commons.io.FileUtils;
import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.util.concurrent.*;
/**
* @Description 线程创建方式三:实现callable接口
* @Author hzx
* @Date 2022-03-26
*/
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 t1 = new TestCallable(
"https://img2022.cnblogs.com/blog/1617979/202203/1617979-20220315222236055-1081286442.png","1.jpg");
TestCallable t2 = new TestCallable(
"https://img2022.cnblogs.com/blog/1617979/202203/1617979-20220315222535845-769752621.png","2.jpg");
TestCallable t3 = new TestCallable(
"https://img2022.cnblogs.com/blog/1617979/202203/1617979-20220315222316724-2013137843.png","3.jpg");
//创建执行服务:
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();
//打印返回结果
System.out.println("rs1返回值:"+rs1);
System.out.println("rs2返回值:"+rs2);
System.out.println("rs3返回值:"+rs3);
//关闭服务
ser.shutdown();
}
}
//下载器
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("IO异常,下载方法出现问题");
}
}
}

输出结果:

下载了文件:1.jpg
下载了文件:3.jpg
下载了文件:2.jpg
rs1返回值:true
rs2返回值:true
rs3返回值:true

callable的好处

  • 1.可以定义返回值;
  • 2.可以抛出异常。
posted @   HZX↑  阅读(42)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· SQL Server 2025 AI相关能力初探
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
点击右上角即可分享
微信分享提示