Handwriting a reentrant lock

Based on the principle:

  1、synchronized

  2, wait, notify method with the use of

 

Code examples are as follows:

  

/ ** 
* handwriting reentrant lock
* /
public class MyLock {
// for determining whether the lock has a
Private Boolean islock;
// for record locking thread
Private the Thread lockThread;
// for recording the number of times the lock
private int LockCount;

public void the synchronized lock () {
// use while reason is that, if the wait is awakened, can continue to determine whether the need to continue to wait
basis // judgment is: has been locked up and locked thread is a thread with
the while (! && islock Thread.currentThread () = lockThread) {
the try {
the wait ();
} the catch (InterruptedException E) {
e.printStackTrace ();
}
}
islock = to true;
IF (lockThread == null) {
lockThread the Thread = .currentThread ();
}
// lock once, increment by one. When used to unlock, determining whether to wake up threads waiting
LockCount ++;
}
public void the synchronized UNLOCK () {
IF (islock && lockThread Thread.currentThread == ()) {
lockCount--;
// 0 represents the current lock object, have all released
IF (LockCount == 0) {
islock = to false;
Notify ();
}
}
}

public static void main (String [] args) {
MethodClass new new MethodClass MC = ();
mc.a ();
}
}
class {MethodClass
MyLock = new new MyLock Lock ();
public void A () {
Lock.lock ();
System.out.println (Thread.currentThread () getName () + ", A.");
B (); // reentrant
lock.unlock ();
}
public void B () {
Lock.lock ();
System.out.println (Thread.currentThread () getName () + ", B.");
lock.unlock ();
}

doubts:
  cross-thread reentrant


Guess you like

Origin www.cnblogs.com/chen--biao/p/11361550.html