Skip to content

Commit c1117a9

Browse files
committed
Synchronized statement example
1 parent 4022255 commit c1117a9

File tree

1 file changed

+39
-0
lines changed

1 file changed

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

0 commit comments

Comments
 (0)