- Java 并发教程
- 并发 - 首页
- 并发 - 概述
- 并发 - 环境设置
- 并发 - 主要操作
- 线程间通信
- 并发 - 同步
- 并发 - 死锁
- 实用程序类示例
- 并发 - ThreadLocal
- 并发 - ThreadLocalRandom
- 锁示例
- 并发 - Lock
- 并发 - ReadWriteLock
- 并发 - Condition
- 原子变量示例
- 并发 - AtomicInteger
- 并发 - AtomicLong
- 并发 - AtomicBoolean
- 并发 - AtomicReference
- 并发 - AtomicIntegerArray
- 并发 - AtomicLongArray
- 并发 - AtomicReferenceArray
- 执行器示例
- 并发 - Executor
- 并发 - ExecutorService
- ScheduledExecutorService
- 线程池示例
- 并发 - newFixedThreadPool
- 并发 - newCachedThreadPool
- newScheduledThreadPool
- newSingleThreadExecutor
- 并发 - ThreadPoolExecutor
- ScheduledThreadPoolExecutor
- 高级示例
- 并发 - Future 和 Callabler
- 并发 - Fork-Join 框架
- 并发集合
- 并发 - BlockingQueue
- 并发 - ConcurrentMap
- ConcurrentNavigableMap
- 并发有用资源
- 并发 - 快速指南
- 并发 - 有用资源
- 并发 - 讨论
Java 并发 - Future 和 Callabler
java.util.concurrent.Callable 对象可以返回由线程进行的计算结果,与只会运行线程的 runnable 接口相反。Callable 对象返回 Future 对象,其提供了用于监视由线程执行的任务进度的多个方法。Future 对象可用于检查 Callable 的状态,然后在线程完成后从 Callable 中检索结果。它还提供了超时功能。
语法
//submit the callable using ThreadExecutor //and get the result as a Future object Future<Long> 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 程序显示了在基于线程的环境中使用 Future 和 Callable。
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
广告