forked from winterbe/java8-tutorial
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLongAccumulator1.java
More file actions
31 lines (23 loc) · 879 Bytes
/
LongAccumulator1.java
File metadata and controls
31 lines (23 loc) · 879 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
package com.winterbe.java8.samples.concurrent;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.atomic.LongAccumulator;
import java.util.function.LongBinaryOperator;
import java.util.stream.IntStream;
/**
* @author Benjamin Winterberg
*/
public class LongAccumulator1 {
public static void main(String[] args) {
testAccumulate();
}
private static void testAccumulate() {
LongBinaryOperator op = (x, y) -> 2 * x + y;
LongAccumulator accumulator = new LongAccumulator(op, 1L);
ExecutorService executor = Executors.newFixedThreadPool(2);
IntStream.range(0, 10)
.forEach(i -> executor.submit(() -> accumulator.accumulate(i)));
ConcurrentUtils.stop(executor);
System.out.format("Add: %d\n", accumulator.getThenReset());
}
}