- Java并发是什么?
- Java并发开发环境配置
- Java并发主要操作
- Java并发线程间通信
- Java并发同步
- Java并发死锁
- 实用类实例
- 锁示例
- 原子变量示例
- 执行者示例
- 线程池示例
- 高级示例
- 并发集合
Java并发Futures和Callables类
java.util.concurrent.Callable
对象可以返回由线程完成的计算结果,而runnable
接口只能运行线程。 Callable
对象返回Future
对象,该对象提供监视线程执行的任务进度的方法。 Future
对象可用于检查Callable
的状态,然后线程完成后从Callable
中检索结果。 它还提供超时功能。
语法
//submit the callable using ThreadExecutor //and get the result as a Future object Future result10 = executor.submit(new FactorialService(10)); //get the result using get method of the Future object //get method waits till the thread execution and then return the result of the execution. Long factorial10 = result10.get();
实例
以下TestThread
程序显示了基于线程的环境中Futures
和Callables
的使用。
import java.util.concurrent.Callable; import java.util.concurrent.ExecutionException; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; public class TestThread { public static void main(final String[] arguments) throws InterruptedException, ExecutionException { ExecutorService executor = Executors.newSingleThreadExecutor(); System.out.println("Factorial Service called for 10!"); Future<Long> result10 = executor.submit(new FactorialService(10)); System.out.println("Factorial Service called for 20!"); Future<Long> result20 = executor.submit(new FactorialService(20)); Long factorial10 = result10.get(); System.out.println("10! = " + factorial10); Long factorial20 = result20.get(); System.out.println("20! = " + factorial20); executor.shutdown(); } static class FactorialService implements Callable<Long>{ private int number; public FactorialService(int number) { this.number = number; } @Override public Long call() throws Exception { return factorial(); } private Long factorial() throws InterruptedException{ long result = 1; while (number != 0) { result = number * result; number--; Thread.sleep(100); } return result; } } }
这将产生以下结果。
Factorial Service called for 10! Factorial Service called for 20! 10! = 3628800 20! = 2432902008176640000
分类导航
- Java教程
- Vim教程
- Swing教程
- Spring教程
- Spring Web Services教程
- Spring MVC教程
- Spring JDBC教程
- Spring Cloud教程
- Spring Boot教程
- Spring Boot CLI教程
- Spring Batch教程
- Spring AOP教程
- PDFBox教程
- JSP教程
- JSF教程
- JPA教程
- Java面向对象设计
- Java设计模式
- Java虚拟机教程
- Java泛型教程
- Java正则表达式教程
- Java数据类型教程
- Java并发编程教程
- Java密码学教程
- Java多线程教程
- Java国际化(i18n)教程
- JavaFX教程
- Java9教程
关注微信小程序
扫描二维码
程序员编程王