java - 为什么第一个线程已经释放了锁,第二个线程却不行?
高洛峰
高洛峰 2017-04-18 10:47:22
0
1
516
public class ReentrantLockDemo {

    private Lock lock = new ReentrantLock();

    public void doSomeThing() {
        System.out.println(Thread.currentThread().getName()+"是否获得了锁:"+lock.tryLock());
        lock.lock();
        try {
            System.out.println(Thread.currentThread().getName());
            Thread.sleep(3000);
        } catch (Exception e) {
        } finally {
            System.out.println(Thread.currentThread().getName()+"释放了锁");
            lock.unlock();
        }

    }

    static class MyRunable implements Runnable {

        private ReentrantLockDemo demo;

        public MyRunable(ReentrantLockDemo demo) {
            this.demo = demo;
        }

        @Override
        public void run() {
            demo.doSomeThing();
        }

    }

    public static void main(String[] args) throws InterruptedException {
    ReentrantLockDemo demo = new ReentrantLockDemo();
        new Thread(new MyRunable(demo)).start();
        Thread.sleep(1000);
        new Thread(new MyRunable(demo)).start();
    }
}

输出:
Thread-0是否获得了锁:true
Thread-0
Thread-1是否获得了锁:false
Thread-0释放了锁

然后就卡在这里了。没有任何结果。可能是发生了死锁。

如果我去掉这句话,一切就是正常的:
System.out.println(Thread.currentThread().getName()+"是否获得了锁:"+lock.tryLock());

请问这是为什么?

高洛峰
高洛峰

拥有18年软件开发和IT教学经验。曾任多家上市公司技术总监、架构师、项目经理、高级软件工程师等职务。 网络人气名人讲师,...

reply all(1)
左手右手慢动作

You are using a reentrant lock. The lock is actually released after calling tryLock的时候,如果当前锁可获得,会立刻获取锁,后面你又调用了一次lock,由于Thread0已经获取了锁,所以可重入锁的state等于2,所以 Thread0 释放锁的时候要unlock twice in Thread0.

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template