forked from hellokaton/learn-java8
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSynchronized1.java
More file actions
52 lines (34 loc) · 1.24 KB
/
Copy pathSynchronized1.java
File metadata and controls
52 lines (34 loc) · 1.24 KB
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
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
package io.github.biezhi.java8.concurrent;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.stream.IntStream;
public class Synchronized1 {
private static final int NUM_INCREMENTS = 10000;
private static int count = 0;
public static void main(String[] args) {
testSyncIncrement();
testNonSyncIncrement();
}
private static void testSyncIncrement() {
count = 0;
ExecutorService executor = Executors.newFixedThreadPool(2);
IntStream.range(0, NUM_INCREMENTS)
.forEach(i -> executor.submit(Synchronized1::incrementSync));
ConcurrentUtils.stop(executor);
System.out.println(" Sync: " + count);
}
private static void testNonSyncIncrement() {
count = 0;
ExecutorService executor = Executors.newFixedThreadPool(2);
IntStream.range(0, NUM_INCREMENTS)
.forEach(i -> executor.submit(Synchronized1::increment));
ConcurrentUtils.stop(executor);
System.out.println("NonSync: " + count);
}
private static synchronized void incrementSync() {
count = count + 1;
}
private static void increment() {
count = count + 1;
}
}