Callable接口

  1. 实现Callable接口,需要返回值类型
  2. 重写call方法,需要抛出异常
  3. 创建目标对象 TestCallable t1 = new TestCallable("https://i0.hdslb.com/bfs/archive/5c2bafe17dd19215a4346c047d5b2cb0c19f958c.png","1.png");
  4. 创建执行服务:ExecutorService s = Executors.newFixedThreadPool(1);
  5. 提交执行:Future r1 = s.submit(t1);
  6. 获取结果:boolean rg = r1.get();
  7. 关闭服务:s.shutdownNow();
package com.thread.callable;


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() {
        WebDownloder webDownloder = new WebDownloder();
        webDownloder.downloder(url,name);
        System.out.println("下载了文件名为"+name);
        return true;
    }


    public static void main(String[] args) throws ExecutionException, InterruptedException {
        TestCallable t1 = new TestCallable("https://i0.hdslb.com/bfs/archive/5c2bafe17dd19215a4346c047d5b2cb0c19f958c.png","1.png");
        TestCallable t2 = new TestCallable("https://i0.hdslb.com/bfs/archive/81612a622ed8b88ebda750ee14b7f9cc3431f43c.jpg@672w_378h_1c.webp","2.jpg");
        TestCallable t3 = new TestCallable("https://i0.hdslb.com/bfs/archive/bc232c2e1886d965d762979d01de4cea7d738150.jpg@672w_378h_1c.webp","3.jpg");

        //创建执行服务
        ExecutorService executorService = Executors.newFixedThreadPool(3);      //拥有3个线程的线程池

        //提交执行
        Future<Boolean> res1 = executorService.submit(t1);
        Future<Boolean> res2 = executorService.submit(t2);
        Future<Boolean> res3 = executorService.submit(t3);

        //获取结果
        Boolean aBoolean1 = res1.get();
        Boolean aBoolean2 = res1.get();
        Boolean aBoolean3 = res1.get();

        System.out.println(aBoolean1);
        System.out.println(aBoolean2);
        System.out.println(aBoolean3);


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

}


//下载器
class WebDownloder{
    //下载方法
    public void downloder(String url,String name){
        try {
            FileUtils.copyURLToFile(new URL(url),new File(name));
        } catch (IOException e) {
            e.printStackTrace();
            System.out.println("IO异常,downloder出现问题");
        }
    }
}
posted @   好12  阅读(50)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 【译】Visual Studio 中新的强大生产力特性
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
点击右上角即可分享
微信分享提示