创建线程的方式:3.实现Callable接口

实现Callable接口

  1. 实现Callable接口,需要返回值类型:implements Callable

  2. 重写call方法,需要抛出异常 :public Boolean call() throws Exception {}

  3. 创建目标对象 :CallableTest callableTest = new CallableTest();

  4. 创建执行服务:ExecutorService service = Executors.newFixedThreadPool(1);

  5. 提交执行:Future future = service.submit(callableTest);

  6. 获取结果:boolean result = future.get();

  7. 关闭服务:service.shutdownNow();

package test;

import java.util.concurrent.*;

//线程创建方式三:实现callable接口
public class CallableTest implements Callable<Boolean> {


    //坐标
    private Integer index;
    

    public CallableTest(Integer index) {
        this.index = index;
    }

    @Override
    public Boolean call() throws Exception {
        System.out.println("执行了call方法" + index);
        return true;
    }

    public static void main(String[] args) throws ExecutionException, InterruptedException {

        CallableTest callableTest1 = new CallableTest(1);
        CallableTest callableTest2 = new CallableTest(2);
        CallableTest callableTest3 = new CallableTest(3);

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

        //提交执行
        Future<Boolean> future1 = service.submit(callableTest1);
        Future<Boolean> future2 = service.submit(callableTest2);
        Future<Boolean> future3 = service.submit(callableTest3);

        //获取结果
        boolean result1 = future1.get();
        boolean result2 = future2.get();
        boolean result3 = future3.get();

        //关闭服务
        service.shutdownNow();

    }


}

callable的好处:
  1. 可以定义返回值

  2. 可以抛出异常

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值