callable接口可以返回结果,如果无法计算返回结果,则会抛出异常。runable接口无法处理返回值问题。

1. Callable介绍

  • Callable接口是一个函数式接口,有一个方法call() 来获取返回值。
  • 如果我们要依赖Callable创建线程,那么可以直接使用lamda表达式进行创建。 ```java package java.util.concurrent;

@FunctionalInterface public interface Callable { /**

  1. * Computes a result, or throws an exception if unable to do so.
  2. *
  3. * @return computed result
  4. * @throws Exception if unable to compute a result
  5. */
  6. V call() throws Exception;

}

<a name="GwIKA"></a>
# 2. Callable创建线程

- 一个类实现callable接口
- 创建类对象
- 创建线程
```java
// 一个类实现callable接口
public class CallableTest implements Callable<Integer> {
    @Override
    public Integer call() throws Exception {
        return 1200;
    }
}

// 创建线程(存在错误)
public static void main(String[] args) {
    CallableTest callableTest = new CallableTest();
    // 这一行代码是报错的!
    new Thread(callableTest);
}

2.1 根据callable创建线程

我们根据Thread类的源码,创建Thread的时候只能传入一个Runable对象,那么我们怎么将callable对象转换为Runable对象呢??

  • 我们可以使用:FutureTask类 ```java // FutureTask 继承了 RunnableFuture public class FutureTask implements RunnableFuture { … }

// RunnableFuture 继承了 Runable类 public interface RunnableFuture extends Runnable, Future { /**

 * Sets this Future to the result of its computation
 * unless it has been cancelled.
 */
void run();

}

那么我们可以将Callable转换为Runable对象,然后就可以传入Thread中进行启动了。
```java
public static void main(String[] args) throws ExecutionException, InterruptedException {
    CallableTest callableTest = new CallableTest();
    FutureTask<Integer> futureTask = new FutureTask<>(callableTest);
    new Thread(futureTask).start();

    while (!futureTask.isDone()) {

    }

    Integer integer = futureTask.get();
    System.out.println(integer);
}

那么既然Callable是函数式接口,我们就可以使用lamda表达式进行简化处理了。

// 我们通过函数式编程来获取futureTask任务
FutureTask<Integer> futureTask = new FutureTask<>(()-> {
    Integer a = 10;
    Integer b = 20;
    return a + b;
});
// 使用线程来启动任务。这里也可以用线程池来处理。
new Thread(futureTask).start();

// 等待线程执行完毕。
while (!futureTask.isDone()) {

}

// 获取线程执行的结果。
Integer integer = futureTask.get();
System.out.println(integer);

2.2 使用线程池执行Callable线程

// 创建线程池
ExecutorService executorService= Executors.newSingleThreadExecutor();
// 使用线程池执行 submit,参数是一个callable对象。返回值是:Future类型,实际类型是FutureTask类型。
Future<Long> submit = executorService.submit(new Callable<Long>() {
    @Override
    public Long call() throws Exception {
        return 100L;
    }
});
Long aLong = submit.get();
System.out.println(aLong);
executorService.shutdown();