synchronized 和 ReentrantLock 的 区别

发布于 2022-08-28 12:50:49 字数 27 浏览 21 评论 0

如题,请简要明了的回答。三克油!!!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

黯然#的苍凉 2022-09-04 12:50:49

使用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.html

Extended 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.
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文