使用synchronized时候,如果程序运行出错,就会抛出异常,但是不会去做清理工作。使用ReentrantLock允许你尝试着获取但最终未获取的锁,这样如果其他人已经获得这个锁,那你就可以离开去执行别的事情,而不是等待直到这个锁被释放。 以上是参考自《think in Java》 在StackOverFlow里也有这样的问题
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.
发布评论
评论(1)
使用
synchronized
时候,如果程序运行出错,就会抛出异常,但是不会去做清理工作。使用ReentrantLock
允许你尝试着获取但最终未获取的锁,这样如果其他人已经获得这个锁,那你就可以离开去执行别的事情,而不是等待直到这个锁被释放。以上是参考自《think in Java》
在StackOverFlow里也有这样的问题