Lock analysis

 
  The Lock interface is the implementation of the lock, which is used to control the way that multiple threads access shared resources. It was introduced in Java 1.5. Before that, the lock of the object could only be obtained by the synchronized method.
  The locks in synchronized are implicitly acquired and released, while the locks in Lock need to be acquired and released explicitly, and at the same time provide features that Synchronized does not have, such as interruptible and timeout acquisition.
  
  Since Synchronized acquires and releases locks implicitly, you can only acquire a lock first, and then release the lock, but in Lock, you can acquire a lock first, and then acquire another lock.
  Then release the previous lock.
  
  At the same time, Lock also provides a way to obtain a conditional lock through newCondition().
 
  Main methods provided:
  void lock(): To acquire the lock, the current thread that calls this method will acquire the lock, and when the lock is acquired, return from this method .
 
  void lockInterruptibly() throws InterruptedException: The lock can be acquired interruptible, and the difference from the lock() method is that this method responds to interruption, that is, the current thread can be interrupted during the acquisition of the lock
 
  boolean tryLock() : try to acquire the lock non-blocking, return immediately after calling this method, return true if it can be acquired, otherwise return false
 
  boolean tryLock(Long time, TimeUnit unit) throws InterruptedException: The lock is acquired over time. It will only return when the current thread acquires the lock, is interrupted, and times out
 
  void unlock(): Release the lock.
 
  Condition newCondition(): Acquires a conditional lock (waiting to notify the component), the component is bound to the current lock, the current thread can call the wait() method of the component only after obtaining the lock, and after the call, the current thread will release the lock.
 
 
   How to use:
 Lock l = ...;
 l.lock();
 try {
   // access the resource protected by this lock
 } finally {
   l.unlock();
 }

 

 
 
 
 
 
 
 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325007693&siteId=291194637