不可重入锁: public class NoReentrantLock { private boolean isLocked = false; public synchronized void lock() throws InterruptedException { while(isLocked) { wait(); } System.out.println("NoReentrantLock.lock is locked"); isLocked = true; } public synchronized void unLock() { System.out.println("NoReentrantLock.unLock is locked"); isLocked = false; notifyAll(); } }
public class NoReentrantLockTest { public static NoReentrantLock noReentrantLock = new NoReentrantLock(); public static void main(String[ ] args) throws InterruptedException { noReentrantLock.lock(); System.out.println("Locked"); noReentrantLock.lock(); System.out.println("Locked Again"); /** * "main" #1 prio=5 os_prio=0 tid=0x0000000004e72800 nid=0x87a0 in Object.wait() [0x0000000004ccf000] java.lang.Thread.State: WAITING (on object monitor) at java.lang.Object.wait(Native Method) - waiting on <0x000000076b801710> (a com.blackfish.bill.billlist.NoReentrantLock) at java.lang.Object.wait(Object.java:502) at com.blackfish.bill.billlist.NoReentrantLock.lock(NoReentrantLock.java:9) - locked <0x000000076b801710> (a com.blackfish.bill.billlist.NoReentrantLock) at com.blackfish.bill.billlist.NoReentrantLockTest.main(NoReentrantLockTest.java:10) * */ } }
可重入锁:
public class ReentrantLockImpl { boolean isLocked = false; Thread lockBy = null; int lockedCount = 0; public synchronized void lock() throws InterruptedException{ Thread thread = Thread.currentThread(); while(isLocked && lockBy != thread) { wait(); } isLocked = true; lockedCount++; lockBy = thread; } public synchronized void unlock() { if(Thread.currentThread() == this.lockBy) { lockedCount--; if(lockedCount == 0) { isLocked = false; notify(); } } } }
public class ReentrantLockTest { public static ReentrantLock reentrantLock = new ReentrantLock(); public static void main(String[ ] args) throws InterruptedException { NoReentrantLock noReentrantLock = new NoReentrantLock(); Thread t1 = new Thread(){ public void run() { try { reentrantLock.lock(); System.out.println("t1 get the lock"); Thread.yield(); Thread.sleep(10); reentrantLock.lock(); System.out.println("t1 get the lock again"); reentrantLock.unlock(); System.out.println("t1 release the lock"); reentrantLock.unlock(); System.out.println("t1 release the lock again"); } catch (Exception e) { System.out.println("t1 throw Exception:" + e); } } }; Thread t2 = new Thread(){ public void run() { try { reentrantLock.lock(); System.out.println("t2 get the lock"); Thread.yield(); Thread.sleep(10); reentrantLock.lock(); System.out.println("t2 get the lock again"); reentrantLock.unlock(); System.out.println("t2 release the lock"); reentrantLock.unlock(); System.out.println("t2 release the lock again"); } catch (Exception e) { System.out.println("t2 throw Exception:" + e); } } }; t1.start(); t2.join(); t2.start(); t2.join(); } } 测试结果:
t2 get the lock
t2 get the lock again
t2 release the lock
t2 release the lock again
t1 get the lock
t1 get the lock again
t1 release the lock
t1 release the lock again