package com.sean.base.threadStudy;
import org.apache.commons.io.FileUtils;
import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.util.concurrent.*;
/**
* 实现callable接口
*
* callable的好处:1可以定义返回值 2可以抛出异常
* @create 2021-02-27 13:31
*/
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() {
WebDownloader1 webDownloader = new WebDownloader1();
webDownloader.downloader(url, name);
System.out.println("下载了文件名为:" + name);
return true;
}
public static void main(String[] args) throws ExecutionException, InterruptedException {
TestCallable d1 = new TestCallable("https://wx2.sinaimg.cn/mw690/002mNrIZly1go19kmrox7j60ku0qvdlv02.jpg", "20.jpg");
TestCallable d2 = new TestCallable("https://wx3.sinaimg.cn/mw690/006fdnrmgy1gnzyl0pmbyj31gi13dtm8.jpg", "21.jpg");
TestCallable d3 = new TestCallable("https://wx2.sinaimg.cn/mw690/001UxQLbly1go15bowahwj60uk0zwgui02.jpg", "22.jpg");
//创建执行服务
ExecutorService ser = Executors.newFixedThreadPool(3);
//提交执行
Future<Boolean> r1 = ser.submit(d1);
Future<Boolean> r2 = ser.submit(d2);
Future<Boolean> r3 = ser.submit(d3);
//获取结果
boolean rs1 = r1.get();
boolean rs2 = r2.get();
boolean rs3 = r3.get();
//关闭服务
ser.shutdown();
}
}
//下载器
class WebDownloader1 {
//下载方法
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异常,download方法出现");
}
}
}
实现callable接口
最新推荐文章于 2024-07-04 07:35:30 发布