-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSynchronizationProblem.java
71 lines (51 loc) · 1.35 KB
/
SynchronizationProblem.java
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
package com.codecafe.concurrency._synchronized;
class SharedResource {
private int x;
public int getX() {
return x;
}
public void setX(int x) {
this.x = x;
}
// run with and without synchronized to see the problem
// 12 should be the correct output
public synchronized void incr() {
int y = getX();
y++;
try {
Thread.sleep(1); // add delay for simulating some amount of processing
} catch (InterruptedException e) {
e.printStackTrace();
}
setX(y);
}
}
class IncrementTask implements Runnable {
private final SharedResource obj;
public IncrementTask(SharedResource obj) {
this.obj = obj;
}
@Override
public void run() {
obj.incr();
}
}
public class SynchronizationProblem {
public static void main(String[] args) {
SharedResource obj = new SharedResource();
obj.setX(10);
Thread t1 = new Thread(new IncrementTask(obj));
Thread t2 = new Thread(new IncrementTask(obj));
long startTime = System.currentTimeMillis();
t1.start();
t2.start();
try {
t1.join(); // wait for thread to finish
t2.join(); // wait for thread to finish
} catch (InterruptedException ex) {
ex.printStackTrace();
}
System.out.println("Total execution time : " + (System.currentTimeMillis() - startTime));
System.out.println(obj.getX());
}
}