-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCounter.java
More file actions
60 lines (54 loc) · 1.58 KB
/
Copy pathCounter.java
File metadata and controls
60 lines (54 loc) · 1.58 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
53
54
55
56
57
58
59
60
import java.util.ArrayList;
import java.util.concurrent.atomic.AtomicInteger;
/**
* @author hyperglory
* @date 05/03/2017 16:02
*
* a Counter comparing between a
* Thread-safe method @safeCount() based on CAS
* and a non Thread-safe method @count()
*/
public class Counter {
private int i = 0;
private AtomicInteger atomicInteger = new AtomicInteger(0);
public static void main(String[] args) {
Counter counter = new Counter();
ArrayList<Thread> threads = new ArrayList<>(600);
long start = System.currentTimeMillis();
for (int i = 0; i < 100; i++) {
Thread thread = new Thread(() -> {
for (int j = 0; j < 10000; j++) {
counter.count();
counter.safeCount();
}
});
threads.add(thread);
}
for (Thread thread : threads) {
thread.start();
}
// wait all threads finish
for (Thread thread : threads) {
try {
thread.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println(counter.i);
System.out.println(counter.atomicInteger.get());
System.out.println(System.currentTimeMillis() - start);
}
public void count() {
i++;
}
public void safeCount() {
for (; ; ) {
int i = atomicInteger.get();
boolean suc = atomicInteger.compareAndSet(i, ++i);
if (suc) {
break;
}
}
}
}