Skip to content

Commit a24aa07

Browse files
author
zhangquanli
committed
程序清单 13-4 带有时间限制的加锁
1 parent 9569de5 commit a24aa07

File tree

1 file changed

+33
-0
lines changed

1 file changed

+33
-0
lines changed
Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
package chapter_13.code_04;
2+
3+
import java.util.concurrent.TimeUnit;
4+
import java.util.concurrent.locks.Lock;
5+
import java.util.concurrent.locks.ReentrantLock;
6+
7+
/**
8+
* 程序清单 13-4 带有时间限制的加锁
9+
*/
10+
public class TimedLocking {
11+
private Lock lock = new ReentrantLock();
12+
13+
public boolean trySendOnSharedLine(String message, long timeout, TimeUnit unit)
14+
throws InterruptedException {
15+
long nanosToLock = unit.toNanos(timeout) - estimatedNanosToSend(message);
16+
if (!lock.tryLock(nanosToLock, TimeUnit.NANOSECONDS)) {
17+
return false;
18+
}
19+
try {
20+
return sendOnSharedLine(message);
21+
} finally {
22+
lock.unlock();
23+
}
24+
}
25+
26+
private boolean sendOnSharedLine(String message) {
27+
return true;
28+
}
29+
30+
long estimatedNanosToSend(String message) {
31+
return message.length();
32+
}
33+
}

0 commit comments

Comments
 (0)