`

(八)Callable与Future

阅读更多

Callable是一个参数化的类型,只有一个方法call。
public interface Callable<V>{
    V call() throw Exception;
}

Future保存异步计算的结果,可以启动一个计算,将Future对象交给某个线程,然后忘掉它。Future对象的所有者在结果计算好之后就可以获得他。
public interface Future<V> {
    boolean cancel(boolean mayInterruptIfRunning);
    boolean isCancelled();
    boolean isDone();
    V get() throws InterruptedException, ExecutionException;
    V get(long timeout, TimeUnit unit) throws InterruptedException, ExecutionException, TimeoutException;
}
第一个get方法的调用被阻塞,直到计算完成。
第二个get方法如果在计算完成之前,如果调用超时,将会抛出一个TimeoutException异常。
如果运行该计算的线程被中断,两个方法都将抛出InterruptedException。如果计算完成get方法立即返回。
如果计算还在进行,isDone()方法返回false;如果完成了,则返回true;
cancel方法用于取消该计算。如果计算还没有开始,它被取消且不再开始。如果计算处于运行之中,那么如果mayInterruptIfRunning参数为true,它就被中断。

FutureTask包装器是一种非常便利的机制,可以将Callable转换成Future和Runnable,它同时实现二者的接口。

    Callable<Integer> myComputation = new CallableSon<Integer>();
    FutureTask<Integer> task = new FutureTask<Integer>(myComputation);
    Thread t = new Thread(task);
    t.start();
    ... ...
    Integer result = task.get();
 

注意:如果想使用Future和Callable必须通过FutureTask,因为Thread只能传入实现了Runnable接口类的实例,FutureTask实现了Runnable。

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics