Loading

Java多线程06-法3实现Callable接口

实现Callable接口

  • 实现Callable接口,需要返回值类型
  • 重写call方法,需要抛出异常
  • 创建目标对象
  • 创建执行服务:ExecutorService ser = Executors.newFixedThreadPool(1)
  • 提交执行Future result1 = ser.submit(t1);
  • 获取结果:boolean r1 = resut1.get()
  • 关闭服务:ser.shutdownNow()
//创建线程法3-实现Callable接口
//callable 优点:可以定义返回值,可以抛出异常
//缺点是实现代码较为繁琐复杂,效率不如前两者高
public class TheradCallable implements Callable<Boolean> {

    private String url;
    private String name;

    public TheradCallable(String url,String name){
        this.url=url;
        this.name=name;
    }
    @Override
    public Boolean call() throws Exception {
        WebDownloader02 webDownloader02=new WebDownloader02();
        webDownloader02.downloader(url,name);
        System.out.println("下载了文件名为:"+name);
        return true;
    }

    public static void main(String[] args) throws ExecutionException, InterruptedException {
        TheradCallable testThread201=new TheradCallable("http://8.136.39.89:9090/asserts/img/portfolio-1.jpg","portfolio-1.jpg");
        TheradCallable testThread202=new TheradCallable("http://8.136.39.89:9090/asserts/img/portfolio-2.jpg","portfolio-2.jpg");
        TheradCallable testThread203=new TheradCallable("http://8.136.39.89:9090/asserts/img/portfolio-3.jpg","portfolio-3.jpg");

        //创建执行服务
        ExecutorService ser = Executors.newFixedThreadPool(3);
        //提交执行
        Future<Boolean> result1 = ser.submit(testThread201);
        Future<Boolean> result2 = ser.submit(testThread202);
        Future<Boolean> result3 = ser.submit(testThread203);
        //获取结果
        boolean r1 = result1.get();
        boolean r2 = result2.get();
        boolean r3 = result3.get();
        //关闭服务
        ser.shutdownNow();
    }
}

class WebDownloader02{
    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异常,downder出现问题");
        }
    }
}

结果展示

下载了文件名为:portfolio-2.jpg
下载了文件名为:portfolio-3.jpg
下载了文件名为:portfolio-1.jpg
posted @ 2022-02-13 23:56  Cn_FallTime  阅读(131)  评论(0编辑  收藏  举报