-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathFullWait.java
More file actions
48 lines (38 loc) · 1.03 KB
/
Copy pathFullWait.java
File metadata and controls
48 lines (38 loc) · 1.03 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
package threadbook.ch14;
public class FullWait extends Object {
private volatile int value;
public FullWait(int initialValue) {
value = initialValue;
}
public synchronized void setValue(int newValue) {
if ( value != newValue ) {
value = newValue;
notifyAll();
}
}
public synchronized boolean waitUntilAtLeast(
int minValue,
long msTimeout
) throws InterruptedException {
if ( msTimeout == 0L ) {
while ( value < minValue ) {
wait(); // wait indefinitely until notified
}
// condition has finally been met
return true;
}
// only wait for the specified amount of time
long endTime = System.currentTimeMillis() + msTimeout;
long msRemaining = msTimeout;
while ( ( value < minValue ) && ( msRemaining > 0L ) ) {
wait(msRemaining);
msRemaining = endTime - System.currentTimeMillis();
}
// May have timed out, or may have met value,
// calc return value.
return ( value >= minValue );
}
public String toString() {
return getClass().getName() + "[value=" + value + "]";
}
}