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;
    }
  }
}

猜你喜欢

转载自blog.csdn.net/chenhao_c_h/article/details/81031986