玩转java多线程 之多线程创建 实现Callable接口

这种创建线程的方法,只做了解
分为以下几步:
第一步: 实现Callable接口,需要返回值类型
第二步: 重写call方法,需要抛出异常
第三步: 创建目标对象
第四步: 创建执行服务

ExecutorService ser = Executors.newFixedThreadPool(1);

第五步:提交执行

Future<Boolean> result1 = ser.submit(t1);

第六步:获取结果

boolean r1 = result1.get()

第七步:关闭服务

ser.shutdownNow()

下面看代码:

package duoxiancheng;

import java.util.concurrent.*;

//线程创建方式三,实现callable接口
public class TestCallable implements Callable<Boolean> {
    private String url; //图片的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://csdnimg.cn/release/blogv2/dist/pc/img/tobarCollectionActive.png", "1. png");
        TestCallable t2 = new TestCallable("https://csdnimg.cn/release/blogv2/dist/pc/img/tobarThumbUpactive.png", "2.png");
        TestCallable t3 = new TestCallable("https://csdnimg.cn/release/blogv2/dist/pc/img/tobarThumbUp.png", "3.png");

        //创建执行服务
        ExecutorService executorService = Executors.newFixedThreadPool(3);

        //提交执行
        Future<Boolean> r1 = executorService.submit(t1);
        Future<Boolean> r2 = executorService.submit(t2);
        Future<Boolean> r3 = executorService.submit(t3);

        boolean result1 = r1.get();
        boolean result2 = r2.get();
        boolean result3 = r3.get();

        System.out.println("result1 = " + result1);
        System.out.println("result2 = " + result2);
        System.out.println("result3 = " + result3);

        executorService.shutdown();
    }
}

在这里插入图片描述
使用callable的好处:
第一:可以定义返回值
第二:可以抛出异常
实现方式也复杂了很多~

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值