java future并行化处理 使用示例
时间: 2023-07-11 15:34:22 浏览: 52
下面是一个使用Java Future并行化处理的示例程序,其中使用了ExecutorService来创建并管理Future对象,使用get方法来等待Future对象完成,并使用isDone方法来检查Future对象是否完成:
```Java
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.*;
public class FutureParallel {
public static void main(String[] args) throws Exception {
ExecutorService executorService = Executors.newFixedThreadPool(5);
List<Future<Integer>> futures = new ArrayList<>();
// 创建5个Future对象,每个对象都会异步执行一个Callable任务
for (int i = 0; i < 5; ++i) {
Future<Integer> future = executorService.submit(new Callable<Integer>() {
@Override
public Integer call() throws Exception {
System.out.println("Task " + Thread.currentThread().getName() + " started");
Thread.sleep(1000);
System.out.println("Task " + Thread.currentThread().getName() + " completed");
return i * 2;
}
});
futures.add(future);
}
// 等待所有的Future对象都完成,并获取它们的结果
for (Future<Integer> future : futures) {
while (!future.isDone()) {
System.out.println("Future not ready");
Thread.sleep(500);
}
System.out.println("Result: " + future.get());
}
executorService.shutdown();
}
}
```
输出结果为:
```
Task pool-1-thread-1 started
Task pool-1-thread-2 started
Task pool-1-thread-3 started
Task pool-1-thread-4 started
Task pool-1-thread-5 started
Task pool-1-thread-1 completed
Result: 0
Task pool-1-thread-2 completed
Result: 2
Task pool-1-thread-3 completed
Result: 4
Task pool-1-thread-4 completed
Result: 6
Task pool-1-thread-5 completed
Result: 8
```
在这个示例程序中,创建了5个Future对象,每个对象都会异步执行一个Callable任务。在等待所有的Future对象都完成时,使用while循环和isDone方法来检查Future对象是否完成,如果未完成,则输出“Future not ready”;如果成功获取到Future对象的结果,则输出“Result: ”和结果值。注意,在使用ExecutorService时,需要在程序结束时调用shutdown方法来关闭线程池,否则程序会一直运行下去。