对于可重入锁,我们目前都知道些什么?
我知道这个class implement Lock interface. 是一种比较高级的锁。
还是三个核心问题:
what is reentrant lock? why would we use it? how to use it?
reentrant lock is a class implement the Lock interface, and provides synchroniation to to methods while accessing resources.
it’s like the keyword synchronized.
it has two features:
- allows threads to enter into the lock on a resource more than one. it has a counter in it. each time we reenter, count plus 1.and for each unlock request, it minues one. so when the hold count is 0, the resource is unlocked.
- it also offers a fairness mechanism. just set true in it’s constructor. which means, the lock will go to the threads which wait for the longest time.
How to use it?
methods in ReentrantLock() class:
lock()
unlock()
tryLock()
getHoldCount()
可以看出大多数都是从lock()里面搞过来的。
使用步骤:
3. Create an object of ReentrantLock
4. Create a worker(Runnable Object) to execute and pass the lock to the object
5. Use the lock() method to acquire the lock on shared resource
6. After completing work, call unlock() method to release the lock