在这里首先介绍下Callable和Future,我们知道通常创建线程的2种方式,一种是直接继承Thread,另外一种就是实现Runnable接口,但是这两种方式创建的线程不返回结果,而Callable是和Runnable类似的接口定义,但是通过实现Callable接口创建的线程可以有返回值,返回值类型可以任意定义。
Callable接口
public interface Callable {
/**
* 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;
}
可以看到,这是一个泛型接口,call()函数返回的类型就是传递进来的V类型。
那么怎么使用Callable呢?一般情况下是配合ExecutorService来使用的,在ExecutorService接口中声明了若干个submit方法的重载版本:
Future submit(Callable task);
Future submit(Runnable task, T result);
Future> submit(Runnable task);
第一个submit方法里面的参数类型就是Callable。Callable一般是和ExecutorService配合来使用的,通过ExecutorService的实例submit得到Future对象。
Future
Future接口如下:
public interface Future {
boolean cancel(boolean mayInterruptIfRunning);// 试图取消对此任务的执行
boolean isCancelled(); // 如果在任务正常完成前将其取消,则返回true
boolean isDone(); // 如果任务已完成(不管是正常还是异常),则返回true
V get() throws InterruptedException, ExecutionException; // 方法用来获取执行结果,这个方法会产生阻塞,会一直等到任务执行完毕才返回;
// 用来获取执行结果,如果在指定时间内,还没获取到结果,就直接返回null;
V get(long timeout, TimeUnit unit) throws InterruptedException, ExecutionException, TimeoutException;
}
Future用于表示异步计算的结果。它的实现类是FutureTask。
如果不想分支线程阻塞主线程,又想取得分支线程的执行结果,就用FutureTask
FutureTask实现了RunnableFuture接口,这个接口的定义如下:
public interface RunnableFuture extends Runnable, Future
{
void run();
}
可以看出RunnableFuture继承了Runnable接口和Future接口,而FutureTask实现了RunnableFuture接口。所以它既可以作为Runnable被线程执行,又可以作为Future得到Callable的返回值。
使用示例
package demo.future;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.*;
/**
* 试验 Java 的 Future 用法
*/
public class FutureTest {
public static class Task implements Callable {
@Override
public String call() throws Exception {
String tid = String.valueOf(Thread.currentThread().getId());
System.out.printf("Thread#%s : in call\n", tid);
return tid;
}
}
public static void main(String[] args) throws InterruptedException, ExecutionException {
List> results = new ArrayList>();
ExecutorService es = Executors.newCachedThreadPool();
for(int i=0; i<100;i++)
results.add(es.submit(new Task()));
for(Future res : results)
System.out.println(res.get());
}
}
终结任务
持有Future对象,可以调用cancel(),并因此可以使用它来中断某个特定任务,如果将ture传递给cancel(),那么它就会拥有该线程上调用interrupt()以停止这个线程的权限。因此,cancel()是一种中断由Executor启动的单个线程的方式。
cancel()一般是搭配get()方法来使用的。比方说,有一种设计模式是设定特定的时间,然后去执行一个作业的线程,如果该作业能够在设定的时间内执行完毕,则直接返回结果,如果不能执行完毕,则中断作业的执行,继续执行下一个作业,在这种模式下,使用Callable和Future来实现是一个非常好的解决方案。