File tree Expand file tree Collapse file tree 1 file changed +33
-0
lines changed
src/main/java/chapter_13/code_04 Expand file tree Collapse file tree 1 file changed +33
-0
lines changed Original file line number Diff line number Diff line change
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
+ }
You can’t perform that action at this time.
0 commit comments