六、Callable、Future、FutureTask
Runable 是一个接口和Thread 一样位于java.lang 包之下,所以才会有 jdk 设计者提出,新建线程的两种方式(JDK1.0)
There are two ways to create a new thread of execution
但是Runable 接口的返回值类型是void,有时候无法满足我们的要求。所以在JDK1.5 的时候由Doug Lea 设计了Callable 接口,所以我们新建线程如果有返回值需求的话则需要实现这个接口。
package java.util.concurrent;
@FunctionalInterface
public interface Callable<V> {
/**
* Computes a result, or throws an exception if unable to do so.
*
* @return computed result
* @throws Exception if unable to compute a result
*/
V call() throws Exception;
}
但是我们知道需要启动线程需要调用Thread 的 start() 方法,而Thread 的构造器
没有一个是可以接收Callable 接口的参数。为了解决这个问题Future、FutureTask 应运而生。
从上图可以看出Future 只是一个接口所以是无法创建对象的,因此需要使用FutureTask,而FutureTask 又实现了Runnable 接口所以他可以投入到Thread 里面执行。
下面上演示代码,演示具体使用:
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;
/**
* Callable、Future、FutureTask 最简单使用演示
* @author ckj
*
*/
public class FutureTest {
static class MyThread implements Callable<Integer> {
public Integer call() throws Exception {
// TODO Auto-generated method stub
return 1;
}
}
public static void main(String[] args) throws InterruptedException, ExecutionException {
FutureTask<Integer> task = new FutureTask<Integer>(new MyThread());
new Thread(task).start();
System.out.println(task.get());
}
}
从上面的代码可以看到将任务task 投入Thread 后使用get()方法获取Callable 返回值,最终打印出1,注意get()方法会阻塞线程直到线程返回结果,后续使用线程池的时候也会遇到这个问题,将会给出解决方法。