对Callable接口的理解

package demo2;

import org.apache.commons.io.FileUtils;

import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.util.concurrent.*;

//线程创建方式三,实现Callable接口
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() {//重写call()方法,注意此处为Boolean类
        WebDownloader webDownloader = new WebDownloader();
        webDownloader.Download(url,name);
        System.out.println("下载类文件名为:"+name);
        return true;
    }

    public static void main(String[] args) throws ExecutionException, InterruptedException {
        //挨个创建对象并且执行构造方法
        TestCallable t1 = new TestCallable("https://www.apple.com.cn/v/imac-24/e/images/overview/colors_lifestyle_fallback__fat816a51hua_large.jpg","p1.jpg");
        TestCallable t2 = new TestCallable("https://img1.baidu.com/it/u=3855106272,1253404534&fm=253&fmt=auto&app=138&f=JPEG?w=678&h=500","p2.jpg");
        TestCallable t3 = new TestCallable("https://img1.baidu.com/it/u=3252704542,3882037568&fm=253&fmt=auto&app=138&f=JPEG?w=889&h=500","p3.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 Download(String url,String name){
        try {//使用FileUtils.copyURLToFile方法将url下的图片保存至文件
            FileUtils.copyURLToFile(new URL(url),new File(name));//快捷键option+command+t调出代码包裹
        } catch (IOException e) {
            e.printStackTrace();
            System.out.println("IO异常");
        }
    }
}
posted @ 2022-10-27 20:27  北极有熊ovo  阅读(23)  评论(0)    收藏  举报