• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录

dengovo

  • 博客园
  • 联系
  • 订阅
  • 管理

公告

View Post

实现Callable

实现Callable接口

  1. 实现Callable接口,需要返回值类型

  2. 重写Call方法,需要抛出异常

  3. 创建目标对象

  4. 创建执行服务

    ExecutorService ser =Executors.newFixedThreadPool(1);

  5. 提交执行:Future result1=ser.submit(t1);

  6. 获取结果:boolean r1=result1.get();

  7. 关闭服务:ser.shutdownNow();

  • 利用callable改造下载图片案例
package com.deng.demo02;

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.可以抛出异常
*/
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 t1 = new TestCallable("http://alifei05.cfp.cn/creative/vcg/800/version23/VCG219486b1842.jpg", "1.jpg");
        TestCallable t2 = new TestCallable("http://tenfei02.cfp.cn/creative/vcg/800/version23/VCG41175510742.jpg","2.jpg");
        TestCallable t3 = new TestCallable("http://alifei05.cfp.cn/creative/vcg/800/version23/VCG21gic5474154.jpg","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);
        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) {
            e.printStackTrace();
            System.out.println("IO异常,downloader方法出现问题");
        }
    }
}

posted on 2022-11-19 12:13  邓了个邓  阅读(41)  评论(0)    收藏  举报

刷新页面返回顶部
 
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3