java.util.concurrent提供了显式的互斥锁机制,允许一些更细腻化的锁操作。我们需要显式创建一个互斥锁对象ReentrantLock。
下面的示例中,线程尝试获取锁,如果获取失败,可以离开去执行一些事情:
- import java.util.concurrent.TimeUnit;
- import java.util.concurrent.locks.ReentrantLock;
- public class LockDemo {
- //显式创建互斥锁
- private ReentrantLock lock = new ReentrantLock();
-
- public void f(){
- //tryLock尝试获取锁,如果成功将立即返回true,反之false
- boolean captured = lock.tryLock();
-
- try {
- System.out.println("f() " + captured);
- } finally {
- if(captured)
- lock.unlock();
- }
- }
-
- public void g(){
- boolean captured = false;
-
- try {
- //在3秒内不断尝试获取锁
- captured = lock.tryLock(2, TimeUnit.SECONDS);
- } catch (InterruptedException e) {
- throw new RuntimeException(e);
- }
-
- try {
- System.out.println("g() " + captured);
- } finally {
- if(captured)
- lock.unlock();
- }
- }
-
- public static void main(String[] args) {
- final LockDemo ld = new LockDemo();
- //测试顺序情况下是否正常
- ld.f();
- ld.g();
-
- //测试并发情况下是否正常
- new Thread(){
- //设为守护线程
- { setDaemon(true); }
- public void run(){
- //lock虽然是private域但是它比较特殊,对外可见
- ld.lock.lock();
- System.out.println("Thread");
- }
- }.start();
-
- //建议调度
- Thread.yield();
-
- //这些方法在匿名线程持有锁的时候尝试获取锁
- ld.f();
- ld.g();
- }
- }
复制代码
|
|