3
3
import java .util .concurrent .ExecutorService ;
4
4
import java .util .concurrent .Executors ;
5
5
import java .util .concurrent .atomic .AtomicInteger ;
6
+ import java .util .function .IntBinaryOperator ;
6
7
import java .util .stream .IntStream ;
7
8
8
9
/**
@@ -12,23 +13,43 @@ public class Atomic1 {
12
13
13
14
private static final int NUM_INCREMENTS = 10000 ;
14
15
15
- private static AtomicInteger count = new AtomicInteger (0 );
16
+ private static AtomicInteger atomicInt = new AtomicInteger (0 );
16
17
17
18
public static void main (String [] args ) {
18
19
testIncrement ();
20
+ testAccumulate ();
21
+ }
22
+
23
+ private static void testAccumulate () {
24
+ atomicInt .set (0 );
25
+
26
+ ExecutorService executor = Executors .newFixedThreadPool (2 );
27
+
28
+ IntStream .range (0 , NUM_INCREMENTS )
29
+ .forEach (i -> {
30
+ Runnable task = () -> {
31
+ IntBinaryOperator operator = (a , b ) -> a + b ;
32
+ atomicInt .accumulateAndGet (i , operator );
33
+ };
34
+ executor .submit (task );
35
+ });
36
+
37
+ ConcurrentUtils .stop (executor );
38
+
39
+ System .out .format ("Accumulate: %d\n " , atomicInt .get ());
19
40
}
20
41
21
42
private static void testIncrement () {
22
- count .set (0 );
43
+ atomicInt .set (0 );
23
44
24
45
ExecutorService executor = Executors .newFixedThreadPool (2 );
25
46
26
47
IntStream .range (0 , NUM_INCREMENTS )
27
- .forEach (i -> executor .submit (count ::incrementAndGet ));
48
+ .forEach (i -> executor .submit (atomicInt ::incrementAndGet ));
28
49
29
50
ConcurrentUtils .stop (executor );
30
51
31
- System .out .format ("Expected=%d; Is=%d" , NUM_INCREMENTS , count .get ());
52
+ System .out .format ("Increment: Expected=%d; Is=%d\n " , NUM_INCREMENTS , atomicInt .get ());
32
53
}
33
54
34
55
}
0 commit comments