-
Notifications
You must be signed in to change notification settings - Fork 2k
Expand file tree
/
Copy pathWaitWithTwoLocks.java
More file actions
36 lines (32 loc) · 1.11 KB
/
WaitWithTwoLocks.java
File metadata and controls
36 lines (32 loc) · 1.11 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
class WaitWithTwoLocks {
private final Object idLock = new Object();
private int id = 0;
private final Object textLock = new Object();
private String text = null;
public void printText() {
synchronized (idLock) {
synchronized (textLock) {
while(text == null)
try {
textLock.wait(); // The lock on "textLock" is released but not the
// lock on "idLock".
}
catch (InterruptedException e) { ... }
System.out.println(id + ":" + text);
text = null;
textLock.notifyAll();
}
}
}
public void setText(String mesg) {
synchronized (idLock) { // "setText" needs a lock on "idLock" but "printText" already
// holds a lock on "idLock", leading to deadlock
synchronized (textLock) {
id++;
text = mesg;
idLock.notifyAll();
textLock.notifyAll();
}
}
}
}