How to lock with ReentrantLock?

喜夏-厌秋 提交于 2019-12-04 07:19:02

问题


I would expect the following test to only print "has been locked" once. BUT it consequently prints the line.

public class LocKTest {
    @Test
    public void testLock() {
        Lock lock = new ReentrantLock();
        while (true) {
            if (lock.tryLock()) {
                //lock.lock(); same result if I include an explicit lock here
                System.out.println("has been locked");
            }
        }
    }
}

As far as I understood, tryLock will lock the ReentrantLock if possible (ie if not locked yet). But obviously this is not the case.

How can I set such a lock threadsafe?


回答1:


The name is ReentrantLock, meaning you can re-enter if you already own the lock.

If you wish to have the thread block, you could use for example a Semaphore with 1 (or more) permits.




回答2:


To quote the documentation about tryLock() (the emphasis in bold added by me):

Acquires the lock if it is not held by another thread and returns immediately with the value true, setting the lock hold count to one

In this case, the current thread is holding the lock, so you ca reenter("re-acquire") it multiple times. If you were to run each iteration of the loop from a different thread, the first one would acquire the lock, and the second would fail to acquire it.




回答3:


Considering Kayamans answer, you could implement your own Lock class:

public class Lock {

    private boolean isLocked = false;

    public synchronized void lock() throws InterruptedException {
        while(isLocked) {
            wait();
        }
        isLocked = true;
    }

    public synchronized void unlock() {
        isLocked = false;
        notify();
    }
}

Use it like this:

public class LocKTest {
    @Test
    public void testLock() {
        Lock lock = new Lock();
        while (true) {
            if (lock.lock()) {
                System.out.println("has been locked"); // prints only once
            }
        }
    }
}

Code example taken from this tutorial.



来源:https://stackoverflow.com/questions/30118842/how-to-lock-with-reentrantlock

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!