同步和重入锁定之间的区别? [英] Difference between synchronized and re-entrant lock?

查看:271
本文介绍了同步和重入锁定之间的区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在Java中使用了 synchronized 关键字和可重入锁定,但我不明白它们之间的区别,或者哪种情况适合于给定的情况。

I have used the synchronized keyword and re-entrant locks in Java, but I don't understand how they differ, or which is appropriate for a given situation.

我如何决定何时使用 synchronized 以及什么时候应该使用可重入锁?

How do I decide when should I use synchronized and when I should use re-entrant locks?

推荐答案

A ReentrantLock 是:


一个可重入的互斥锁相同的基本行为和
语义作为使用synchronized
方法和语句访问的隐式监视器锁,但具有扩展功能。

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.

扩展功能包括:


  1. 能够拥有多个每个监视器的条件变量。使用synchronized关键字的监视器只能有一个。这意味着可重入锁支持多个wait()/ notify()队列。

  2. 进行锁定的能力公平。同步块是不公平的。

  1. 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.
  2. The ability to make the lock fair. Synchronized blocks are unfair.

[fair]锁定有权授予对等待时间最长的线程的访问权限。否则此锁定不保证任何特定的访问顺序。

"[fair] locks favor granting access to the longest-waiting thread. Otherwise this lock does not guarantee any particular access order."


  • 能否检查是否持有锁。

  • 获取等待的线程列表的能力锁定。

  • 可重入锁的缺点是:


    1. 需要添加import语句。

    2. 需要在try / finally块中包装锁定获取。这使得它比synchronized关键字更难看。

    3. synchronized 关键字可以放在方法定义中,避免了对块的需要这减少了嵌套。

    1. Need to add import statement.
    2. Need to wrap lock acquisitions in a try/finally block. This makes it more ugly than the synchronized keyword.
    3. The synchronized keyword can be put in method definitions which avoids the need for a block which reduces nesting.

    摘要

    synchronized 关键字在语法上更好,但是Reentrant锁具有更多功能。

    The synchronized keyword is syntactically nicer, but the Reentrant lock has more features.

    这篇关于同步和重入锁定之间的区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

    查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆