2016-11-23 09:05:26 -08:00
|
|
|
// concurrent/ParallelStreamPuzzle2.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.function.*;
|
|
|
|
import java.util.stream.*;
|
|
|
|
import java.util.concurrent.*;
|
2017-01-02 14:20:54 -08:00
|
|
|
import java.util.concurrent.atomic.*;
|
2016-07-05 14:46:09 -06:00
|
|
|
import java.nio.file.*;
|
|
|
|
|
|
|
|
public class ParallelStreamPuzzle2 {
|
2017-05-01 17:43:21 -06:00
|
|
|
public static final Deque<String> trace =
|
2016-07-05 14:46:09 -06:00
|
|
|
new ConcurrentLinkedDeque<>();
|
|
|
|
static class
|
|
|
|
IntGenerator implements Supplier<Integer> {
|
2017-01-02 14:20:54 -08:00
|
|
|
private AtomicInteger current =
|
|
|
|
new AtomicInteger();
|
|
|
|
public Integer get() {
|
|
|
|
trace.add(current.get() + ": " +
|
2016-07-05 14:46:09 -06:00
|
|
|
Thread.currentThread().getName());
|
2017-01-02 14:20:54 -08:00
|
|
|
return current.getAndIncrement();
|
2016-07-05 14:46:09 -06:00
|
|
|
}
|
|
|
|
}
|
2016-12-31 14:57:31 -08:00
|
|
|
public static void
|
|
|
|
main(String[] args) throws Exception {
|
|
|
|
List<Integer> x =
|
|
|
|
Stream.generate(new IntGenerator())
|
|
|
|
.limit(10)
|
|
|
|
.parallel()
|
|
|
|
.collect(Collectors.toList());
|
2016-07-05 14:46:09 -06:00
|
|
|
System.out.println(x);
|
|
|
|
Files.write(Paths.get("PSP2.txt"), trace);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
/* Output:
|
2017-05-10 11:45:39 -06:00
|
|
|
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
|
2016-07-05 14:46:09 -06:00
|
|
|
*/
|