ReentrantLock 重入锁(下)
前沿:
ReentrantLock reentrantLock = new ReentrantLock(); reentrantLock.lock(); System.out.println("Hello World1"); reentrantLock.lock(); System.out.println("Hello World2"); reentrantLock.unlock(); reentrantLock.unlock();
结果:
Hello World1
Hello World2
2. 释放锁多一次
ReentrantLock reentrantLock = new ReentrantLock(); reentrantLock.lock(); System.out.println("Hello World1"); reentrantLock.lock(); System.out.println("Hello World2"); reentrantLock.unlock(); reentrantLock.unlock(); reentrantLock.unlock();
结果:
Exception in thread "main" Hello World1
Hello World2
java.lang.IllegalMonitorStateException
at java.util.concurrent.locks.ReentrantLock$Sync.tryRelease(ReentrantLock.java:151)
at java.util.concurrent.locks.AbstractQueuedSynchronizer.release(AbstractQueuedSynchronizer.java:1261)
at java.util.concurrent.locks.ReentrantLock.unlock(ReentrantLock.java:457)
at com.juxinli.docs.test.Main.main(Main.java:21)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at com.intellij.rt.execution.application.AppMain.main(AppMain.java:140)
通过对比很明显发现同一个线程可以重复获取两次锁,但释放三次就出现异常。
3. 多线程锁机制
ReentrantLock reentrantLock = new ReentrantLock(); new Thread(new Runnable() { @Override public void run() { try { Thread.sleep(100); reentrantLock.lock(); System.out.println("Hello World1"); reentrantLock.unlock(); } catch (InterruptedException e) { e.printStackTrace(); } } }).start(); new Thread(new Runnable() { @Override public void run() { reentrantLock.lock(); try { Thread.sleep(1000); System.out.println("Hello World2"); reentrantLock.unlock(); } catch (InterruptedException e) { e.printStackTrace(); } } }).start();
结果:
Hello World2
Hello World1
很明显按照逾期结果输出。
posted on 2017-09-11 17:36 LittlePony 阅读(660) 评论(0) 编辑 收藏 举报