简体   繁体   English

java ReentrantLock tryLock() 误区

[英]java ReentrantLock tryLock() misunderstanding

    ReentrantLock l = new ReentrantLock(true);
            Reader[] readers = new Reader[2];
    
            for (int i = 0; i < readers.length; i++) {
                readers[i] = new Reader(l);
            }
            for (int i = 0; i < readers.length; i++) {
                readers[i].start();
            }

public class Reader extends Thread {

    private ReentrantLock l;

    public Reader(ReentrantLock l) {
        this.l = l;
    }

    @Override
    public void run() {
        try {
              l.tryLock();
            for (int i = 0; i < 5; i++) {
                System.out.println(Thread.currentThread().getName() + " i =  " + i);
                Thread.sleep(500);
            }
//            l.unlock(); // although it commented the code not hanged why?
                   } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}

according to my understanding to tryLock() Acquires the lock if it is not held by another thread and returns immediately now in my case i have two threads suppose thread_0 get lock now i have two questions : Q1: why thread_1 still enter the critical section after l.tryLock() isn't it locked by thread_0;根据我对 tryLock() 的理解,如果它没有被另一个线程持有,则获取锁并立即返回在我的情况下我有两个线程假设 thread_0 现在获得锁我有两个问题: Q1:为什么 thread_1 之后仍然进入临界区l.tryLock() 是不是被thread_0锁了; Q2: isn't it supposes to my code to be hanged because thread_0 doesn't release the lock #thanks advance Q2:是不是我的代码会被挂起,因为 thread_0 没有释放锁#thanks Advance

Your code is entering the critical section because, tryLock() is not a blocking function, it will return true or false immediately, and proceed with the "Critical Section" code snippet below.您的代码正在进入临界区,因为 tryLock() 不是阻塞函数,它会立即返回 true 或 false,然后继续下面的“临界区”代码片段。

In the documentation of tryLock() you can read在 tryLock() 的文档中,您可以阅读

If the lock is held by another thread then this method will return immediately with the value false.如果锁被另一个线程持有,那么这个方法将立即返回 false 值。

So you need to call lock() method, which waits until the lock is released by another reader.因此,您需要调用 lock() 方法,该方法会等待另一个读取器释放锁。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM