1. Function
(1) The Lock method to acquire the lock supports interruption, does not acquire after timeout, and is non-blocking
(2) Improves semantics, Where to lock and where to unlock must be written out
(3) Lock explicit lock can bring us good flexibility, but at the same time we must manually release the lock
(4) Support Condition object
(5) Allow multiple reading threads to access shared resources at the same time
2.lock usage
// 获取锁 void lock() // 如果当前线程未被中断,则获取锁 void lockInterruptibly() // 返回绑定到此 Lock 实例的新 Condition 实例 Condition newCondition() // 仅在调用时锁为空闲状态才获取该锁 boolean tryLock() // 如果锁在给定的等待时间内空闲,并且当前线程未被中断,则获取锁 boolean tryLock(long time, TimeUnit unit) // 释放锁 void unlock()
lock(), tryLock (), tryLock(long time, TimeUnit unit) and lockInterruptibly() are used to acquire locks. The unLock() method is used to release the lock. The newCondition() method is used for communication between threads.
The above is the detailed content of What are the ways to use Lock in Java?. For more information, please follow other related articles on the PHP Chinese website!