JAVA并发-Future-诺禾

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

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

public interface Future {
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 。

通过Future的cancel()取消任务
可以通过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

猜你喜欢

转载自blog.csdn.net/yyone123/article/details/107793622