多线程之Callable
来源:互联网 发布:淘宝优惠券shipinwj 编辑:程序博客网 时间:2024/06/08 08:53
To demonstrate, the following example creates separate Callable instances for each word passed in on the command line and sums up their length. Each Callable will just calculate the sum of its individual word. The set of Future objects are saved to acquire the calculated value from each. If the order of the returned values needed to be preserved, a List could be used instead.
import java.util.*;import java.util.concurrent.*;public class CallableExample { public static class WordLengthCallable implements Callable { private String word; public WordLengthCallable(String word) { this.word = word; } public Integer call() { return Integer.valueOf(word.length()); } } public static void main(String args[]) throws Exception { ExecutorService pool = Executors.newFixedThreadPool(3); Set<Future<Integer>> set = new HashSet<Future<Integer>>(); for (String word: args) { Callable<Integer> callable = new WordLengthCallable(word); Future<Integer> future = pool.submit(callable); set.add(future); } int sum = 0; for (Future<Integer> future : set) { sum += future.get(); } System.out.printf("The sum of lengths is %s%n", sum); System.exit(sum); }}The WordLengthCallable saves each word and uses the word's length as the value returned by the call() method. This value could take some time to generate but in this case is known immediately. The only requirement of call() is the value is returned at the end of the call. When the get() method of Future is later called, the Future will either have the value immediately if the task runs quickly, as in this case, or will wait until the value is done generating. Multiple calls to get() will not cause the task to be rerun in the thread.
原文:https://blogs.oracle.com/CoreJavaTechTips/entry/get_netbeans_6
- 多线程之Callable
- 多线程之6-------Callable & Future
- 多线程之 Callable Future FutureTask
- Java多线程之Callable接口的实现
- Java多线程之Callable接口的实现
- Java多线程之Callable接口的实现
- Java多线程之Callable接口的实现
- Java多线程之Callable接口的实现
- Java多线程之Callable接口的实现
- Java多线程之Callable接口的实现
- Java多线程之Callable接口的实现
- Java多线程之 Callable、Future和FutureTask
- Java多线程之Callable接口的实现
- Java多线程之Callable接口(一)
- Java多线程之Callable接口的实现
- Java多线程之Callable接口的实现
- Java多线程之Callable接口的实现
- Java多线程之Callable接口的实现
- oracle 10g 11g 使用dos命令启动服务
- 准大二了,给大一来个总结吧
- 如何维护大项目-修复bug
- VC++ Win7关闭UAC 写注册表
- 树
- 多线程之Callable
- 一步步搭建Ubuntu环境——卸载liboffice
- Struts Exception GenericsObjectTypeDeterminer
- ppp拨号脚本配置
- mssql 2008 里, 如何把log文件的清空。
- 通过COM技术实现Windows Shell编程(图)
- 直接写IO端口0x64完成计算机重启操作实现暴力关机
- RING0级暴力搜索内存检测系统隐藏进程(或ROOTKIT)(实测可运行) .
- Remove Duplicates from Sorted Array