1. Implementation method


class X {
   private final ReentrantLock lock = new ReentrantLock();
  // ...

   public void m() {
    lock.lock();  // block until condition holds
     try {
       // ... method body
     } finally {
      lock.unlock()
     }
  }
 }
Copy the code

2. Analysis of characteristics

1, lock type is exclusive lock, default non-fair lock, thread interrupt to remove blocking

2, fair lock and unfair lock essential difference:

An unfair lock can be acquired as long as the lock is not held (via the CAS setting tag), otherwise it is inserted into the tail of the queue (internal bidirectional list implementation queue).

A fair lock can be acquired if and only if the lock is not held and the queue has only the head thread (i.e. the queue is empty) or the head thread is the current thread. Otherwise, the lock is inserted at the end of the queue (internal bidirectional list implementation queue).

3. Whether it is a fair lock or an unfair lock, if the thread currently holding the lock releases the lock, the order of acquiring the lock is in accordance with the queue (THE node-line program joining the queue first obtains the lock).

4. API methods for internal blocking and unblocking threads are

LockSupport.park(this);

LockSupport.unpark(s.thread);

ConditionObject (the object returned by newCondition in reentrantLock. Java) corresponds to the method that an exclusive lock can call

Await () adds the current node to the blocking queue and blocks the current thread

Signal () unblocks the next node in the queue

SignalAll () unblocks all nodes in the queue

Iii. Analysis of class structure

4. Call process analysis

1. Every time a new node is added after the lock method is called, if no lock is obtained, the node will be added to the blocking queue and the current thread will be blocked

2. Unlock is called to unblock a node behind the head node