【锁】求解:关于lock.unlock以后 第二个线程没法得到锁的问题

代码以下:code

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");
            }
        }
    }
}

执行结果以下:get

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()方法是未生效的吗?百思不得其解
跪求大佬解惑it

相关文章
相关标签/搜索