ReentrantLock 重入锁(下)
Posted 沁园下的一缕残云
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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
很明显按照逾期结果输出。
以上是关于ReentrantLock 重入锁(下)的主要内容,如果未能解决你的问题,请参考以下文章