`
- 浏览:
362161 次
- 性别:
-
在Java中,如果需要设定代码执行的最长时间,即超时,可以用Java线程池ExecutorService类配合Future接口来实现。 Future接口是Java标准API的一部分,在java.util.concurrent包中。Future接口是Java线程Future模式的实现,可以来进行异步计算。
Future模式可以这样来描述:我有一个任务,提交给了Future,Future替我完成这个任务。期间我自己可以去做任何想做的事情。一段时间之后,我就便可以从Future那儿取出结果。就相当于下了一张订货单,一段时间后可以拿着提订单来提货,这期间可以干别的任何事情。其中Future 接口就是订货单,真正处理订单的是Executor类,它根据Future接口的要求来生产产品。
Future接口提供方法来检测任务是否被执行完,等待任务执行完获得结果,也可以设置任务执行的超时时间。这个设置超时的方法就是实现Java程序执行超时的关键。
Future接口是一个泛型接口,严格的格式应该是Future<V>,其中V代表了Future执行的任务返回值的类型。 Future接口的方法介绍如下:
boolean cancel (boolean mayInterruptIfRunning) 取消任务的执行。参数指定是否立即中断任务执行,或者等等任务结束
boolean isCancelled () 任务是否已经取消,任务正常完成前将其取消,则返回 true
boolean isDone () 任务是否已经完成。需要注意的是如果任务正常终止、异常或取消,都将返回true
V get () throws InterruptedException, ExecutionException 等待任务执行结束,然后获得V类型的结果。InterruptedException 线程被中断异常, ExecutionException任务执行异常,如果任务被取消,还会抛出CancellationException
V get (long timeout, TimeUnit unit) throws InterruptedException, ExecutionException, TimeoutException 同上面的get功能一样,多了设置超时时间。参数timeout指定超时时间,uint指定时间的单位,在枚举类TimeUnit中有相关的定义。如果计算超时,将抛出TimeoutException
Future的实现类有java.util.concurrent.FutureTask<V>即 javax.swing.SwingWorker<T,V>。通常使用FutureTask来处理我们的任务。FutureTask类同时又实现了Runnable接口,所以可以直接提交给Executor执行。使用FutureTask实现超时执行的代码如下:
Java代码 收藏代码
ExecutorService executor = Executors.newSingleThreadExecutor();
FutureTask<String> future =
new FutureTask<String>(new Callable<String>() {//使用Callable接口作为构造参数
public String call() {
//真正的任务在这里执行,这里的返回值类型为String,可以为任意类型
}});
executor.execute(future);
//在这里可以做别的任何事情
try {
result = future.get(5000, TimeUnit.MILLISECONDS); //取得结果,同时设置超时执行时间为5秒。同样可以用future.get(),不设置执行超时时间取得结果
} catch (InterruptedException e) {
futureTask.cancel(true);
} catch (ExecutionException e) {
futureTask.cancel(true);
} catch (TimeoutException e) {
futureTask.cancel(true);
} finally {
executor.shutdown();
}
不直接构造Future对象,也可以使用ExecutorService.submit方法来获得Future对象,submit方法即支持以 Callable接口类型,也支持Runnable接口作为参数,具有很大的灵活性。使用示例如下:
Java代码 收藏代码
ExecutorService executor = Executors.newSingleThreadExecutor();
FutureTask<String> future = executor.submit(
new Callable<String>() {//使用Callable接口作为构造参数
public String call() {
//真正的任务在这里执行,这里的返回值类型为String,可以为任意类型
}});
//在这里可以做别的任何事情
//同上面取得结果的代码
利用Future接口实现程序执行超时大致用法就这么多,改天需要研究下Future接口的内部实现,特别是设定执行超时的实现。
分享到:
Global site tag (gtag.js) - Google Analytics
相关推荐
/home/data/anaconda3/lib/python3.7/site-packages/pymysql/cursors.py:170: Warning: (1681, 'Integer display width is deprecated and will be removed in a future release.') result = self._query(query) ...
Architecture and Design for the Future Internet addresses the Networks of the Future and the Future Internet, focusing on networks aspects, offering both technical and non-technical perspectives....
python库。 资源全名:future-0.12.0.tar.gz
future-0.18.2-py3-none-any.whl 官网太难下载了
03 The Future of Architecture.pdf 04 j2ee_leon.pdf 04 j2ee_richard.pdf 05 SOA软件架构的实现.pdf 06 1Design Patterns.pdf 06 2Agile Software Development.pdf 06 3IsDesignDead.pdf 07 Architecture.pdf 07 ...
python安装打包依赖包-future-0.18.1.tar.gz
Springer.Future.Internet.Technologies.and.Trends.First.International.ConferenceSpringer.Future.Internet.Technologies.and.Trends.First.International.ConferenceSpringer.Future.Internet.Technologies.and....
future-0.18.2-py3-none-any.whl ,官网下载有点慢 future-0.18.2-py3-none-any.whl ,为什么我把积分改为0,他又会自己变成29啊
Orthogonal Waveforms and Filter Banks for Future Communication Systems provides an up-to-date account of orthogonal filter bank-based multicarrier (FBMC) systems and their applications in modern and ...
The Future of Retail - To the extent that there are two distinct sides to the argument, the position of Offline-to-Online (O2O) advocates is that, as more offline retailers are closing, brick-and-...
Crafting Your Research Future
[竞争大未来].Competing.for.the.Future.(美)哈梅尔&普拉哈拉德.扫描版.pdf [竞争大未来].Competing.for.the.Future.(美)哈梅尔&普拉哈拉德.扫描版.pdf
The Future Evolution of High-Performance Microprocessors
c++11多线程编程库中的future库的使用实例,供多线程编程参考学习
Document that explain the future of PowerBuilder
主要介绍了Java使用Callable和Future创建线程操作,结合实例形式分析了java使用Callable接口和Future类创建线程的相关操作技巧与注意事项,需要的朋友可以参考下
future, currently in their school or pre-school years, are likely to access and interact with digital resources in five to ten years’ time. This is to help library and information services to ...
Reinforcement Learning_ Past, Present, and Future Perspectives,强化学习:过去、现在和未来(NeurIPS 2019),by Katja Hofmann,非常全面的强化学习总结英文资料,值得学习参考。
Big Data Analytics in Future Power Systems by:Ahmed F. Zobaa and Trevor J. Bihl ISBN-10 书号: 1138095885 ISBN-13 书号: 9781138095885 Edition 版本: 1 出版日期: 2018-09-24 pages 页数: (188) $99.95 ...