【Java多线程】之十三:Java Callable Future Example
来源:互联网 发布:chart.js 提示文字 编辑:程序博客网 时间:2024/05/15 08:13
In last few posts, we learned a lot about java threads but sometimes we wish that a thread could return some value that we can use. Java 5 introduced java.util.concurrent.Callable interface in concurrency package that is similar to Runnable interface but it can return any Object and able to throw Exception.
Callable interface use Generic to define the return type of Object. Executors class provide useful methods to execute Callable in a thread pool. Since callable tasks run in parallel, we have to wait for the returned Object. Callable tasks return java.util.concurrent.Future object. Using Future we can find out the status of the Callable task and get the returned Object. It provides get() method that can wait for the Callable to finish and then return the result.
Future provides cancel() method to cancel the associated Callable task. There is an overloaded version of get() method where we can specify the time to wait for the result, it’s useful to avoid current thread getting blocked for longer time. There are** isDone()and **isCancelled() methods to find out the current status of associated Callable task.
Here is a simple example of Callable task that returns the name of thread executing the task after one second. We are using Executor framework to execute 100 tasks in parallel and use Future to get the result of the submitted tasks.
Click here learn about more
- 【Java多线程】之十三:Java Callable Future Example
- Java多线程之 Callable、Future和FutureTask
- Java多线程之Callable和Future
- Java的多线程之Callable与Future
- Java多线程之Callable、Future和FutureTask
- java多线程之Callable和Future
- (十八)java多线程之Callable Future
- java多线程之Callable和Future
- Java多线程之Callable、Future和FutureTask
- Java多线程 Callable Future FutureTask
- java多线程Callable和Future
- Java - 多线程Callable、Executors、Future
- 【Java多线程】-Callable,Future,FutureTask
- Java多线程--Future与Callable
- java 多线程( Future Callable)
- Java 多线程 callable future实例
- Java多线程--Callable和Future
- Java并发之Callable、Future
- 注意:STM32库函数中未用到的参数也一定要初始化
- 102. Binary Tree Level Order Traversal
- Android的历史
- Python-Selenium2做Web自动化测试(12)-上传文件、下载文件、调用 JavaScript、控制浏览器滚动条
- 8.Python基础 面向对象的基本概念
- 【Java多线程】之十三:Java Callable Future Example
- LintCode-通配符匹配
- 随记
- socket 通信关于bind那点事
- 用VC6扩展CButton类制作风格独特的按钮
- 暑假第3周工作周报
- CSS hack 总结
- sdnu 1087.过河(NOIP 2005 提高组)DP状态压缩
- AngularJS初学习