其他分享
首页 > 其他分享> > 实现Callable接口(了解即可)

实现Callable接口(了解即可)

作者:互联网

 

查看代码

package com.lei.study02;

import com.lei.study.Thread1;
import org.apache.commons.io.FileUtils;

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


public class TestThread implements Callable<Boolean> {
    private String url; //网络图片地址
    private String name; //保存的文件名

    public TestThread(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 {
        TestThread t3=new TestThread("https://www.icode9.com/i/l/?n=22&i=blog/2696501/202204/2696501-20220404143439429-968657608.png","图片3");

        //创建执行服务
        ExecutorService ser= Executors.newFixedThreadPool(1);

        //提交执行
        Future<Boolean> r1=ser.submit(t3);

        //获取结果
        boolean rs1=r1.get();

        //打印返回值
        System.out.println(rs1);

        //关闭服务
        ser.shutdown();
    }

}
//下载器
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方法出现问题");
        }
    }
}

 

标签:name,url,接口,Callable,即可,new,import,public,String
来源: https://www.cnblogs.com/evelei/p/16119592.html