|
3 | 3 | // We make no guarantees that this code is fit for any purpose. |
4 | 4 | // Visit http://OnJava8.com for more book information. |
5 | 5 | import java.util.concurrent.*; |
| 6 | +import java.util.stream.*; |
6 | 7 |
|
7 | 8 | public class CachedThreadPool { |
8 | | - public static void main(String[] args) |
9 | | - throws InterruptedException { |
| 9 | + public static void main(String[] args) { |
10 | 10 | ExecutorService exec = |
11 | 11 | Executors.newCachedThreadPool(); |
12 | | - for(int id = 0; id < 10; id++) |
13 | | - exec.execute(new SleepAndPrintTask(id)); |
| 12 | + IntStream.range(0, 10) |
| 13 | + .mapToObj(NapTask::new) |
| 14 | + .forEach(exec::execute); |
14 | 15 | exec.shutdown(); |
15 | 16 | } |
16 | 17 | } |
17 | 18 | /* Output: |
18 | | -SleepAndPrintTask[2] pool-1-thread-3 |
19 | | -SleepAndPrintTask[9] pool-1-thread-10 |
20 | | -SleepAndPrintTask[6] pool-1-thread-7 |
21 | | -SleepAndPrintTask[5] pool-1-thread-6 |
22 | | -SleepAndPrintTask[7] pool-1-thread-8 |
23 | | -SleepAndPrintTask[8] pool-1-thread-9 |
24 | | -SleepAndPrintTask[0] pool-1-thread-1 |
25 | | -SleepAndPrintTask[1] pool-1-thread-2 |
26 | | -SleepAndPrintTask[4] pool-1-thread-5 |
27 | | -SleepAndPrintTask[3] pool-1-thread-4 |
| 19 | +NapTask[2] pool-1-thread-3 |
| 20 | +NapTask[9] pool-1-thread-10 |
| 21 | +NapTask[6] pool-1-thread-7 |
| 22 | +NapTask[5] pool-1-thread-6 |
| 23 | +NapTask[7] pool-1-thread-8 |
| 24 | +NapTask[8] pool-1-thread-9 |
| 25 | +NapTask[0] pool-1-thread-1 |
| 26 | +NapTask[1] pool-1-thread-2 |
| 27 | +NapTask[4] pool-1-thread-5 |
| 28 | +NapTask[3] pool-1-thread-4 |
28 | 29 | */ |
0 commit comments