TryLock

《Java并发编程实战》这本书的缺点是有些例子给的不完整,所以想直接复制代码、运行看结果还是比较费力的,第13章显示锁的一个例子就是这样。在这种情况下,只能自己写或求助于互联网。下面用网上的一个小例子演示带有超时功能的tryLock的基本用法。关于Lock和同步代码块的区别以及更深入的研究,后续博文会有所涉及。

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
package com.freelemon.concurrency.chp13;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
/**
* Created with IntelliJ IDEA.
* User: hongbin
* Date: 14-11-15
* Time: 上午11:41
* To change this template use File | Settings | File Templates.
*/
public class ReentrantLockingDemo {
private final Lock lock = new ReentrantLock();
public static void main(final String... args){
new ReentrantLockingDemo().go();
}
private void go(){
new Thread(newRunnable(), "Thread-1").start();
new Thread(newRunnable(), "Thread-2").start();
}
private Runnable newRunnable(){
return new Runnable(){
@Override
public void run() {
do{
try{
if (lock.tryLock(500, TimeUnit.MILLISECONDS)){
try{
System.out.println("Locked thread " + Thread.currentThread().getName());
Thread.sleep(1000);
} finally {
lock.unlock();
System.out.println("unlocked locked thread " + Thread.currentThread().getName());
}
break;
} else {
System.out.println("unable to lock thread " + Thread.currentThread().getName() + ", will try again.");
}
} catch (InterruptedException e) {
e.printStackTrace();
}
} while(true);
}
};
}
}

运行结果如下:

1
2
3
4
5
Locked thread Thread-2
unable to lock thread Thread-1, will try again.
unlocked locked thread Thread-2
Locked thread Thread-1
unlocked locked thread Thread-1

参考资料

PS