-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSynchronizationProblemWithStatic.java
69 lines (51 loc) · 1.14 KB
/
SynchronizationProblemWithStatic.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
package com.codecafe.concurrency._synchronized;
class Sample1 {
static int a = 5; // static variables are NOT thread-safe
int b = 10;
public int getB() {
return b;
}
public void increment() {
synchronized (Sample1.class) {
int c = a;
c++;
try {
Thread.sleep(2);
} catch (InterruptedException e) {
e.printStackTrace();
}
a = c;
}
synchronized (this) {
b++;
}
}
}
class IncTask implements Runnable {
Sample1 obj;
public IncTask(Sample1 obj) {
this.obj = obj;
}
@Override
public void run() {
obj.increment();
}
}
public class SynchronizationProblemWithStatic {
public static void main(String[] args) {
Sample1 obj1 = new Sample1();
Sample1 obj2 = new Sample1();
Thread t1 = new Thread(new IncTask(obj1));
Thread t2 = new Thread(new IncTask(obj2));
t1.start();
t2.start();
try {
t1.join();
t2.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.printf("a = %d%n", Sample1.a);
System.out.printf("obj1 - b = %d%nobj2 - b = %d", obj1.getB(), obj2.getB());
}
}