首页 > 其他分享 >实现Callable接口

实现Callable接口

时间:2023-03-16 19:34:13浏览次数:44  
标签:name 实现 接口 Callable url Demo01 println new String

package edu.wtbu;

import org.apache.commons.io.FileUtils;

import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.util.concurrent.*;

/*
callable的好处
1.可以定义返回值
2.可以抛出异常
*/
public class Demo01 implements Callable {
private String url;//网络图片地址
private String name;//保存的文件名

public Demo01(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 {
Demo01 demo01 = new Demo01("https://b0.bdstatic.com/ugc/yQ2BNBkVVb_E0IpmtFRrbwb7809eeba6400217fa19fdb7ec0ca44d.jpg@h_1280","1.jpg");
Demo01 demo02 = new Demo01("https://img2.baidu.com/it/u=3393071480,1773077460&fm=253&fmt=auto&app=120&f=JPEG?w=1421&h=800","2.jpg");
Demo01 demo03 = new Demo01("https://pic.rmb.bdstatic.com/bjh/02f9ad62ee8b9fd91d97fccc033b4868.jpeg@wm_2,t_55m+5a625Y+3L0FZU1UzMjQ=,fc_ffffff,ff_U2ltSGVp,sz_18,x_12,y_12","3.jpg");

//创建执行服务
ExecutorService ser = Executors.newFixedThreadPool(3);

//提交执行
Future<Boolean> r1 = ser.submit(demo01);
Future<Boolean> r2 = ser.submit(demo02);
Future<Boolean> r3 = ser.submit(demo03);

//获取结果
boolean rs1=r1.get();
boolean rs2=r2.get();
boolean rs3=r3.get();

System.out.println(rs1);
System.out.println(rs2);
System.out.println(rs3);

//关闭服务
ser.shutdownNow();
}
}

//下载器
class WebDownloader{
//下载方法
public void downloader(String url,String name){
try {
FileUtils.copyURLToFile(new URL(url),new File(name));
} catch (IOException e) {
System.out.println("IO异常");
}

}
}

标签:name,实现,接口,Callable,url,Demo01,println,new,String
From: https://www.cnblogs.com/123456dh/p/17223886.html

相关文章