Java Reference
In-Depth Information
public static Stream<Integer> countTo(int value) {
if (value <= 0) {
throw new IllegalArgumentException("Need a positive value to count up to, but we were
given " + value);
}
return Stream.iterate(1, i -> i + 1).limit(value).parallel();
}
}
// Listing6.java
public class Listing6 {
public static void main(String[] args) {
System.out.println("\n\n\nPARALLEL");
NumberStreamFactory.countTo(200).parallel().map(i -> {
System.out.println("map: " + i +
" Thread: " + Thread.currentThread().getName());
return i;
}
).forEach(i ->
System.out.println("forEach: " + i +
" Thread: " + Thread.currentThread().getName())
);
System.out.println("\n\n\nSEQUENTIAL");
NumberStreamFactory.countTo(200).sequential().map(i -> {
System.out.println("map: " + i +
" Thread: " + Thread.currentThread().getName());
return i;
}
).forEach(i ->
System.out.println("forEach: " + i +
" Thread: " + Thread.currentThread().getName())
);
}
}
/* SAMPLE RESULT
PARALLEL
map: 13 Thread: ForkJoinPool.commonPool-worker-4
map: 132 Thread: main
map: 163 Thread: ForkJoinPool.commonPool-worker-1
map: 32 Thread: ForkJoinPool.commonPool-worker-3
forEach: 32 Thread: ForkJoinPool.commonPool-worker-3
map: 182 Thread: ForkJoinPool.commonPool-worker-2
forEach: 182 Thread: ForkJoinPool.commonPool-worker-2
map: 33 Thread: ForkJoinPool.commonPool-worker-3
...
Search WWH ::




Custom Search