OnJava8-Examples/concurrent/CachedThreadPool3.java

48 lines
1.2 KiB
Java
Raw Normal View History

2016-11-23 09:05:26 -08:00
// concurrent/CachedThreadPool3.java
2016-12-30 17:23:13 -08:00
// (c)2017 MindView LLC: see Copyright.txt
2016-07-05 14:46:09 -06:00
// We make no guarantees that this code is fit for any purpose.
2016-09-23 13:23:35 -06:00
// Visit http://OnJava8.com for more book information.
2016-07-05 14:46:09 -06:00
import java.util.*;
import java.util.concurrent.*;
import java.util.stream.*;
public class CachedThreadPool3 {
public static Integer
extractResult(Future<Integer> f) {
2016-07-05 14:46:09 -06:00
try {
return f.get();
} catch(Exception e) {
throw new RuntimeException(e);
}
}
public static void main(String[] args)
throws InterruptedException {
ExecutorService exec =
Executors.newCachedThreadPool();
List<CountingTask> tasks =
IntStream.range(0, 10)
.mapToObj(CountingTask::new)
.collect(Collectors.toList());
List<Future<Integer>> futures =
exec.invokeAll(tasks);
Integer sum = futures.stream()
.map(CachedThreadPool3::extractResult)
2016-07-05 14:46:09 -06:00
.reduce(0, Integer::sum);
System.out.println("sum = " + sum);
exec.shutdown();
}
}
/* Output:
2 pool-1-thread-3 100
2016-07-27 11:12:11 -06:00
6 pool-1-thread-7 100
5 pool-1-thread-6 100
2016-07-05 14:46:09 -06:00
7 pool-1-thread-8 100
2016-07-22 14:45:35 -06:00
4 pool-1-thread-5 100
2016-07-05 14:46:09 -06:00
9 pool-1-thread-10 100
2016-07-27 11:12:11 -06:00
3 pool-1-thread-4 100
0 pool-1-thread-1 100
1 pool-1-thread-2 100
8 pool-1-thread-9 100
2016-07-05 14:46:09 -06:00
sum = 1000
*/