JAVA并发-Future

java.util.concurrent.Future, 代表着通过异步计算返回结果,创建异步任务时,返回一个java Future对象。异步任务完成后,可以通过启动任务时返回的Future对象访问结果,一些Java的内置并发实用程序,比如ExecutorService,从它们的一些方法返回一个java Future对象。在ExecutorService中,当提交一个Callable以便并发(异步)执行时,它返回一个Future

Future接口定义

为了理解Future接口如何工作, 下面是接口的定义:

public interface Future<V> {
    boolean cancel(boolean mayInterruptIfRunning)
    V       get();
    V       get(long timeout, TimeUnit unit);
    boolean isCancelled();
    boolean isDone();
}

 

每一个方法下都会讲到,但是正如你所见,Future 并没有那么高级。

Future获取结果

前面讲到, Future代表了可以获取结果的异步任务。获取结果,可以通过Future 两个get()方法中的一个,get()方法都可以返回结果,但是返回的结果也是泛型(就是指定类的对象,而不仅仅是Object)。下面是通过Future get()方法获取返回结果:

Future future = ... // get Future by starting async task

// do something else, until ready to check result via Future

// get result from Future
try {
    Object result = future.get();
} catch (InterruptedException e) {
    e.printStackTrace();
} catch (ExecutionException e) {
    e.printStackTrace();
}

 

如果在异步任务没完成之前调用get()方法将阻塞直到任务完成才返回结果。可以调用带有时间参数的get()方法,当超时了会抛异常,看下例子:

try {
    Object result =
        future.get(1000, TimeUnit.MILLISECONDS);
} catch (InterruptedException e) {

} catch (ExecutionException e) {

} catch (TimeoutException e) {
    // thrown if timeout time interval passes
    // before a result is available.
}

 

上面的示例最多等待1000毫秒,可以获得结果,如果1000毫秒内没有结果返回,将抛TimeoutException 

通过Futurecancel()取消任务

可以通过Future  实例的cancel()方法取消异步任务,异步任务的实现必须支持取消任务,如果不支持,调用cancel()方法没有任何作用:

future.cancel();

检查任务是否完成

可以通过调用Future isDone()检查异步任务是否完成:

Future future = ... // Get Future from somewhere

if(future.isDone()) {
    Object result = future.get();
} else {
    // do something else
}

 

检查任务是否取消

同样可以通过调用Future isCancelled()方法检查异步任务是否已经取消

Future future = ... // get Future from somewhere

if(future.isCancelled()) {

} else {

}

 

参考:http://tutorials.jenkov.com/java-util-concurrent/java-future.html

           https://blog.csdn.net/cgsyck/article/details/107692471

           https://blog.csdn.net/cgsyck/article/details/107709421

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值