Simple Java code is not reentrant and reentrant lock locks implemented

Multi-threaded Java wait () method, and notify () method:

  • wait (): blocks the current thread
  • notify (): evoke the wait () blocked thread

These two methods are in pairs and used to perform these two methods, there is a premise that the current thread must obtain monitor its object ( "lock"), otherwise it will throw an exception IllegalMonitorStateException, so the two methods It must be called sync block code inside.
 

Non-reentrant lock:

public class Lock{
    private boolean isLocked = false;
    public synchronized void lock() throws InterruptedException{
        while(isLocked){    
            wait();
        }
        isLocked = true;
    }
    public synchronized void unlock(){
        isLocked = false;
        notify();
    }
}
//使用
class Count{
    Lock lock = new Lock();
    public void print(){
        lock.lock();
        doAdd();
        lock.unlock();
    }
    public void doAdd(){
        lock.lock();
        //do something
        lock.unlock();
    }
}

Reentrant lock:

public class Lock{
    boolean isLocked = false;
    Thread  lockedBy = null;
    int lockedCount = 0;
    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();
            }
        }
    }
}
//使用
class Count{
    Lock lock = new Lock();
    public void print(){
        lock.lock();
        doAdd();
        lock.unlock();
    }
    public void doAdd(){
        lock.lock();
        //do something
        lock.unlock();
    }
}

 

Guess you like

Origin blog.csdn.net/qq_42239765/article/details/90750091