How to lock with ReentrantLock?

前端 未结 3 1723
名媛妹妹
名媛妹妹 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:41

    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.

提交回复
热议问题