其他分享
首页 > 其他分享> > 【多线程】线程创建方式三:实现callable接口

【多线程】线程创建方式三:实现callable接口

作者:互联网

线程创建方式三:实现callable接口

代码示例:

import org.apache.commons.io.FileUtils;

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

/**
 * @Description 线程创建方式三:实现callable接口
 * @Author hzx
 * @Date 2022-03-26
 */
/**
 * callable的好处
 * 1.可以定义返回值;
 * 2.可以抛出异常。
 */

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() {
        WebDownloader webDownloader = new WebDownloader();
        webDownloader.downloader(url, name);
        System.out.println("下载了文件:"+name);
        return true;
    }

    public static void main(String[] args) throws ExecutionException, InterruptedException {
        TestCallable t1 = new TestCallable(
                "https://www.icode9.com/i/l/?n=22&i=blog/1617979/202203/1617979-20220315222236055-1081286442.png","1.jpg");
        TestCallable t2 = new TestCallable(
                "https://www.icode9.com/i/l/?n=22&i=blog/1617979/202203/1617979-20220315222535845-769752621.png","2.jpg");
        TestCallable t3 = new TestCallable(
                "https://www.icode9.com/i/l/?n=22&i=blog/1617979/202203/1617979-20220315222316724-2013137843.png","3.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返回值:"+rs1);
        System.out.println("rs2返回值:"+rs2);
        System.out.println("rs3返回值:"+rs3);

        //关闭服务
        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异常,下载方法出现问题");
        }
    }
}

输出结果:

下载了文件:1.jpg
下载了文件:3.jpg
下载了文件:2.jpg
rs1返回值:true
rs2返回值:true
rs3返回值:true

callable的好处

标签:name,TestCallable,callable,url,线程,new,返回值,多线程,String
来源: https://www.cnblogs.com/hzxll/p/16059841.html