【狂神说Java】实现多线程:Callable接口

Callable接口

  1. 实现Callable接口,需要返回值类型
  2. 重写call方法,需要抛出异常
  3. 创建目标对象
  4. 创建执行服务
  5. 提交执行
  6. 获取结果
  7. 关闭服务

修改下载图片

import java.util.concurrent.*;

public class StartCallable implements Callable<Boolean> {


    private String url = ""; // 网络图片地址
    private String name = ""; // 保存路径

    // 构造器,初始化地址
    public StartCallable(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; // Callable多一个返回值
    }


    // 启动线程
    public static void main(String[] args) throws ExecutionException, InterruptedException {
        String url = "https://img0.bdstatic.com/static/searchdetail/img/logo-2X_2dd9a28.png";
        String name = "C:\\Users\\Jie7\\IdeaProjects\\Test\\src\\baidulogo";
        // 多线程,启动,无序
        StartCallable picThread1 = new StartCallable(url, name +"1.png");
        StartCallable picThread2 = new StartCallable(url, name +"2.png");
        StartCallable picThread3 = new StartCallable(url, name +"3.png");
        // 创建执行服务,三个线程
        ExecutorService ser = Executors.newFixedThreadPool(3);
        // 提交执行
        Future<Boolean> r1 = ser.submit(picThread1);
        Future<Boolean> r2 = ser.submit(picThread2);
        Future<Boolean> r3 = ser.submit(picThread3);
        // 可以获取返回值
//        boolean re1 = r1.get();
//        boolean re2 = r2.get();
//        boolean re3 = r3.get();
        // 关闭服务
        ser.shutdown();
    }
}
上一篇:pandas的Series源码解读


下一篇:【已解决】Intel NUC10 拔插USB口/登录QQ/蓝牙连接等导致显示器黑屏