java线程学习(三):Callable和Future

之前提到过线程的两种创建方式,今天说一下callable,与Runnable接口功能相似,用来指定线程的任务。其中的call()方法,用来返回线程任务执行完毕后的结果,call方法可抛出异常。可以理解为callable是可以抛出异常且有返回值的Runnable。而Future则是用来接收Callable的返回值,他们同样都是JDK5新增并发包concurrent下的接口。

Callable的使用

首先看看Callable的源码

正如之前所说,与Runnable接口十分相似,可以看得出来 定义了泛型的返回值,抛出了异常。

我们来看一个简单的例子。

public class CallableDemo {

  public static void main(String[] args) throws ExecutionException, InterruptedException {
    // 创建callable对象
    MyCallable myCallable = new MyCallable();
    FutureTask<Integer> result = new FutureTask<>(myCallable);
    Thread thread = new Thread(result);
    thread.start();
    // 取得返回值
    Integer num = result.get();
    System.out.println(num);
  }

  public static class MyCallable implements Callable<Integer>{

    @Override
    public Integer call() throws Exception {
      return 1;
    }
  }
}

线程池中的Callable

下面我们看一下在线程池中如何使用callable

public class ThreadPoolCallable {

  public static void main(String[] args) throws ExecutionException, InterruptedException {
    // 创建一个只有一个线程的线程池
    ExecutorService singleThreadExecutor = Executors.newSingleThreadExecutor();
    Callable<Integer> tCallable = new MyCallable();
    Future<Integer> future = singleThreadExecutor.submit(tCallable);
    // 取得返回值
    Integer result = future.get();
    System.out.println(result);
  }

  public static class MyCallable implements Callable<Integer> {

    @Override
    public Integer call() throws Exception {
      return 1;
    }
  }
}

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值