九、实现Callable接口(了解即可)

步骤:

  1. 实现Callable接口,需要返回值类型
  2. 重写call方法,需要抛出异常
  3. 创建目标对象
  4. 创建执行服务:ExecutorService ser = Executors.newFixedThreadPool(1);
  5. 提交执行:Future<Boolean> result1 = ser.submit(t1);
  6. 获取结果: boolean r1 = result1.get();
  7. 关闭服务: ser.shutdownNow();

 

改造同步下载网络图片:

public class CallableThread implements Callable {


    private String url;

    private String name;

    public CallableThread(String url, String name) {
        this.url = url;
        this.name = name;
    }

    @Override
    public Boolean call() throws Exception {
        WebDownloader webDownloader = new WebDownloader();
        webDownloader.downloader(this.url,this.name);
        return true;
    }

    public static void main(String[] args) throws ExecutionException, InterruptedException {

        CallableThread t1 = new CallableThread("https://yjsc.gxu.edu.cn/images/2021-for100.jpg","./callable/1.jpg");
        CallableThread t2 = new CallableThread("https://yjsc.gxu.edu.cn/images/2022yjsy.jpg","./callable/2.jpg");
        CallableThread t3 = new CallableThread("https://yjsc.gxu.edu.cn/images/2022newyear.jpg","./callable/3.jpg");
        CallableThread t4 = new CallableThread("https://yjsc.gxu.edu.cn/images/202010banner.jpg","./callable/4.jpg");

        ExecutorService service = Executors.newFixedThreadPool(4);

        Future<Boolean> f1 = service.submit(t1);
        Future<Boolean> f2 = service.submit(t2);
        Future<Boolean> f3 = service.submit(t3);
        Future<Boolean> f4 = service.submit(t4);

        Boolean rs1 = f1.get();
        Boolean rs2 = f2.get();
        Boolean rs3 = f3.get();
        Boolean rs4 = f4.get();
        service.shutdownNow();
    }


}


class WebDownloader{

    public void  downloader(String url, String name) {
        try {
            FileUtils.copyURLToFile(new URL(url),new File(name));
            System.out.println("图片:"+name+",下载完成");
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

}
posted @ 2022-05-14 03:13  Epiphany8Z  阅读(70)  评论(0编辑  收藏  举报