本文介绍了同步和重入锁定之间的区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我在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 是:
扩展功能包括:
- 能够拥有多个。使用synchronized关键字的监视器只能有一个。这意味着可重入锁支持多个wait()/ notify()队列。
- 进行锁定的能力。同步块是不公平的。
- 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. Synchronized blocks are unfair.
可重入锁的缺点是:
- 需要添加import语句。
- 需要在try / finally块中包装锁定获取。这使得它比synchronized关键字更难看。
-
synchronized
关键字可以放在方法定义中,避免了对块的需要这减少了嵌套。
- 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.
摘要
synchronized
关键字在语法上更好,但是Reentrant锁具有更多功能。
The synchronized
keyword is syntactically nicer, but the Reentrant lock has more features.
这篇关于同步和重入锁定之间的区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!