How to lock with ReentrantLock?

前端 未结 3 1695
名媛妹妹
名媛妹妹 2021-01-29 09:49

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          


        
3条回答
  •  一生所求
    2021-01-29 10:35

    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.

提交回复
热议问题