如题,请简要明了的回答。三克油!!!
使用synchronized
时候,如果程序运行出错,就会抛出异常,但是不会去做清理工作。使用ReentrantLock
允许你尝试着获取但最终未获取的锁,这样如果其他人已经获得这个锁,那你就可以离开去执行别的事情,而不是等待直到这个锁被释放。
以上是参考自《think in Java》
在StackOverFlow里也有这样的问题
A reentrant mutual exclusion Lock with the same basic behavior and semantics as the implicit monitor lock accessed using synchronized methods and statements, but with extended capabilities.
From: http://docs.oracle.com/javase/1.5.0/docs/api/java/util/concurrent/locks/ReentrantLock.htmlExtended capabilities include:
- The ability to have more than one condition variable per monitor. Monitors that use the synchronized keyword can only have one. This means reentrant locks support more than one wait()/notify() queue.
- The ability to make the lock "fair". "[fair] locks favor granting access to the longest-waiting thread. Otherwise this lock does not guarantee any particular access order." Synchronized blocks are unfair.
- The ability to check if the lock is being held.
- The ability to get the list of threads waiting on the lock.
The disadvantages of reentrant locks are:
- Need to add import statement.
- Need to wrap lock acquisitions in a try/finally block. This makes it more ugly than the synchronized keyword.
- The synchronized keyword can be put in method definitions which avoids the need for a block which reduces nesting.