Locks may be implemented reentrant

/ ** 
 * @ClassName Lock 
 * @Description reentrant lock 
 * @author Administrator 
 * @date 2019/6/8 16:58 
 * @Version 1.0 
 ** / 
public class Lock { 
    Boolean = isLocked to false; 
    the Thread lockedBy = null; 
    lockedCount = 0 int; 

    / ** 
     * reentrant means: a thread can enter any of it already has a lock synchronized block of code 
     * @throws InterruptedException 
     * / 

    / ** 
     * we designed two threads call print ( ) method, the first thread calls print () method to get the lock, enter the lock () method, 
     * The initial lockedBy is null, it will not enter hangs while the current thread, 
     * but incremental lockedCount and for the record lockBy the first thread. Then the first thread enters doAdd () method, 
     * Due to the same process, so it will not enter while hang, then increment lockedCount, 
     * when the second thread attempts to lock, due isLocked = true, so he will not get the lock,
     * 直到第一个线程调用两次unlock()将lockCount递减为0,才将标记为isLocked设置为false
     * @throws InterruptedException
     */

    public synchronized void lock() throws InterruptedException{
        Thread thread = Thread.currentThread();

        while(isLocked && lockedBy != thread){
            wait();
        }

        isLocked = true;
        lockedCount++;
        lockedBy = thread;
    }

    public synchronized void unlock(){
        if(Thread.currentThread() == this.lockedBy){
            lockedCount--;
            if(lockedCount == 0){
                isLocked = false;
                notify();
            }
        }
    }
}

  

Guess you like

Origin www.cnblogs.com/wylwyl/p/10991193.html
May