锁求解关于lockunlock之后-第二个线程无法获得锁的问题

35次阅读

共计 953 个字符,预计需要花费 3 分钟才能阅读完成。

代码如下:

public class SynchronizedAndLockDemo {public static void main(String[] args) throws InterruptedException {Writer writer = new Writer();

        Thread t1 = new Thread(() -> {writer.testTryLock();

        });
        t1.setName("t1");

        Thread t2 = new Thread(() -> {writer.testTryLock();
        });
        t2.setName("t2");


        t1.start();
        t2.start();}

}


class Writer {Lock lock = new ReentrantLock();

    public void testTryLock() {String threadName = Thread.currentThread().getName();

        System.out.println(threadName + ":" + lock.tryLock());

        try {if (lock.tryLock(5000, TimeUnit.MILLISECONDS)) {lock.lock();
                System.out.println(threadName + "get the lock ...");
//                Thread.sleep(2000);
//                System.out.println(threadName + "sleep 2s");
            } else {System.out.println(threadName + "can't get the lock ...");
            }


        } catch (Exception e) { } finally {if (lock.tryLock()) {lock.unlock();
                System.out.println(threadName + "unlock");
            }
        }
    }
}

执行结果如下:

t1:true
t2:false
t1 get the lock ...
t1 unlock
t2 can't get the lock ...

按理说,t1 释放锁后 t2 是在 5 秒内获取不到锁才终止,但是 t1 在 5s 内已经完成了任务,并且释放了锁,为什么 t2 仍然无法获得锁呢?是 t1 尚未释放锁吗?那 lock.unlock()方法是未生效的吗?百思不得其解
跪求大佬解惑

正文完
 0