1. Description
Before the lock interface appeared, Java programs relied on the synchronized keyword to implement the lock function. After Java SE 5, the lock interface was added to the concurrent package. (and related implementation classes) are used to implement the lock function. It provides a synchronization function similar to the synchronized keyword.
It just needs to explicitly acquire and release the lock when using it. Although it lacks the convenience of implicit acquisition and release of locks (provided by synchronized blocks or methods), it has the operability of lock acquisition and release, interruptible acquisition of locks, and timeout acquisition. Locks and other synchronized keywords do not have synchronization features.
2. Main method
lock() Add lock
unlock() Release lock
tryLock() This method ensures that when a lock is needed, it is in an unlocked state. Returning true means it is unlocked; returning false means it is locked.
new Condition() Returns a Condition instance of the current lock
Because the code of locking every time is inefficient, ReadWriteLock has been extended, and the implementation class mainly includes ReentrantReadWriteLock
When we use the lock function, due to the shortcomings of synchronized, it will bring some inconvenience. In the new Java version, the concept of lock interface has been produced. It can be said that in the acquisition and release of locks Implemented relevant technical operations.
Collections in Java are mainly divided into four categories:
1. List: ordered, repeatable;
2. Queue: ordered and repeatable;
3. Set: non-repeatable;
4. Map: unordered, with unique keys and non-unique values.
The above is the detailed content of What is the Lock interface in Java?. For more information, please follow other related articles on the PHP Chinese website!