public class CustomRentrantLock { public static void main(String[] args) { LockCustom LockCustom=new ReentrantLockCustom(); MyRunnable myRunnable=new MyRunnable(LockCustom); new Thread(myRunnable,"Thread-1").start(); new Thread(myRunnable,"Thread-2").start(); } } class MyRunnable implements Runnable{ LockCustom lockCustom; public MyRunnable(LockCustom LockCustom) { this.lockCustom=LockCustom; } public void run(){ System.out.println(Thread.currentThread().getName() +" is Waiting to acquire LockCustom"); lockCustom.lock(); System.out.println(Thread.currentThread().getName() +" has acquired LockCustom."); try { Thread.sleep(5000); System.out.println(Thread.currentThread().getName() +" is sleeping."); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println(Thread.currentThread().getName() +" has released LockCustom."); lockCustom.unlock(); } } interface LockCustom { void lock(); void unlock(); boolean tryLock(); } class ReentrantLockCustom implements LockCustom { int lockHoldCount; long lockingThreadId; ReentrantLockCustom() { lockHoldCount = 0; } public synchronized void lock() { if (lockHoldCount == 0) { lockHoldCount++; lockingThreadId = Thread.currentThread().getId(); } else if (lockHoldCount > 0 && lockingThreadId == Thread.currentThread().getId()) { lockHoldCount++; } else { try { wait(); lockHoldCount++; lockingThreadId = Thread.currentThread().getId(); } catch (InterruptedException e) { e.printStackTrace(); } } } public synchronized void unlock() { if (lockHoldCount == 0) throw new IllegalMonitorStateException(); lockHoldCount--; if (lockHoldCount == 0) notify(); } public synchronized boolean tryLock() { if (lockHoldCount == 0) { lock(); return true; } else return false; } }