This repository was archived by the owner on Jan 28, 2018. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathSynchronizedProof.java
More file actions
88 lines (69 loc) · 2.26 KB
/
Copy pathSynchronizedProof.java
File metadata and controls
88 lines (69 loc) · 2.26 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
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
package javaaplication5;
import static java.lang.Thread.sleep;
import java.util.concurrent.atomic.AtomicInteger;
class SynchronizedProof {
public static void main(String[] args) throws InterruptedException {
sleep(500);
normalIssue();
sleep(500);
synchronizedIssue();
}
public static void normalIssue() throws InterruptedException {
CountProblemNormal pt = new CountProblemNormal();
Thread t1 = new Thread(pt, "t1");
Thread t2 = new Thread(pt, "t2");
long startTimeT1 = System.nanoTime();
t1.start();
t2.start();
t1.join();
t2.join();
while (pt.getCount() != 2000) {
//Busy Waiting until it complete increment
}
long endTimeT1 = System.nanoTime();
System.out.printf("Normal thread = %.8f seconds%n", (endTimeT1 - startTimeT1) / 1000000000.0);
}
public static void synchronizedIssue() throws InterruptedException {
CountProblemSynchronized pt = new CountProblemSynchronized();
Thread t1 = new Thread(pt, "t1");
Thread t2 = new Thread(pt, "t2");
long startTimeT1 = System.nanoTime();
t1.start();
t2.start();
t1.join();
t2.join();
while (pt.getCount() != 2000) {
//Busy Waiting until it complete increment
}
long endTimeT1 = System.nanoTime();
System.out.printf("Synchronized thread = %.8f seconds%n", (endTimeT1 - startTimeT1) / 1000000000.0);
}
}
class CountProblemNormal implements Runnable {
private static AtomicInteger atomicCounter = new AtomicInteger(0);
private static int count;
@Override
public void run() {
for (int i = 1; i <= 1000; i++) {
count = atomicCounter.incrementAndGet();
}
}
public int getCount() {
return this.count;
}
}
class CountProblemSynchronized implements Runnable {
private static AtomicInteger atomicCounter = new AtomicInteger(0);
private static int count;
@Override
public void run() {
for (int i = 1; i <= 1000; i++) {
synchronized (this) {
count = atomicCounter.incrementAndGet();
}
}
}
public int getCount() {
return this.count;
}
}