-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLockDemo5.java
More file actions
105 lines (92 loc) · 2.16 KB
/
Copy pathLockDemo5.java
File metadata and controls
105 lines (92 loc) · 2.16 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
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
package four;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
public class LockDemo5 {
public static void main(String[] args) {
MyService5 myService5 = new MyService5();
MyThread5A myThread5A = new MyThread5A(myService5);
myThread5A.setName("A");
myThread5A.start();
MyThread5B myThread5B = new MyThread5B(myService5);
myThread5B.setName("B");
myThread5B.start();
}
}
class MyService5 {
private Lock lock = new ReentrantLock();
private Condition condition = lock.newCondition();
private boolean value = false;
public void getValue() {
try {
lock.lock();
if (value == false) {
System.out.println("getValue() " + Thread.currentThread().getName());
condition.await();
} else {
condition.signal();
}
value = true;
lock.unlock();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
public void setValue() {
try {
lock.lock();
if (value == true) {
System.out.println("setValue() " + Thread.currentThread().getName());
condition.await();
} else {
condition.signal();
}
value = false;
lock.unlock();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
class MyThread5A extends Thread {
private MyService5 myService5;
public MyThread5A(MyService5 myService5) {
this.myService5 = myService5;
}
public void testGetValue() {
myService5.getValue();
}
@Override
public void run() {
while (true) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
testGetValue();
}
}
}
class MyThread5B extends Thread {
private MyService5 myService5;
public MyThread5B(MyService5 myService5) {
this.myService5 = myService5;
}
public void testSetValue() {
myService5.setValue();
}
@Override
public void run() {
while (true) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
testSetValue();
}
}
}