Skip to content

Commit e8cc2fc

Browse files
committed
Test AtomicInteger
1 parent b81681c commit e8cc2fc

File tree

2 files changed

+35
-1
lines changed

2 files changed

+35
-1
lines changed
Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
package com.winterbe.java8.samples.concurrent;
2+
3+
import java.util.concurrent.ExecutorService;
4+
import java.util.concurrent.Executors;
5+
import java.util.concurrent.atomic.AtomicInteger;
6+
import java.util.stream.IntStream;
7+
8+
/**
9+
* @author Benjamin Winterberg
10+
*/
11+
public class Atomic1 {
12+
13+
private static final int NUM_INCREMENTS = 10000;
14+
15+
private static AtomicInteger count = new AtomicInteger(0);
16+
17+
public static void main(String[] args) {
18+
testIncrement();
19+
}
20+
21+
private static void testIncrement() {
22+
count.set(0);
23+
24+
ExecutorService executor = Executors.newFixedThreadPool(2);
25+
26+
IntStream.range(0, NUM_INCREMENTS)
27+
.forEach(i -> executor.submit(count::incrementAndGet));
28+
29+
ConcurrentUtils.stop(executor);
30+
31+
System.out.format("Expected=%d; Is=%d", NUM_INCREMENTS, count.get());
32+
}
33+
34+
}

src/com/winterbe/java8/samples/concurrent/Synchronized1.java

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,7 @@ public class Synchronized1 {
1111

1212
private static final int NUM_INCREMENTS = 10000;
1313

14-
private static int count = 1;
14+
private static int count = 0;
1515

1616
public static void main(String[] args) {
1717
testSyncIncrement();

0 commit comments

Comments
 (0)