java - 在Java中,监视器和锁有什么区别

标签 java locking synchronized

使用synchronized关键字的方法,使用javap命令查看字节码,发现使用了monitor,如果实现synchronized的时候可以调用monitor,我的理解是这样吧?如果不正确请更正。他们之间是什么关系?锁和监视器是什么关系?

最佳答案

来自Locks and Synchronization的官方文档:

  • Synchronization is built around an internal entity known as the intrinsic lock or monitor lock. (The API specification often refers to this entity simply as a "monitor.")
  • Every object has an intrinsic lock associated with it. By convention, a thread has to acquire the object's monitor lock before accessing them, and then release the monitor lock when it's done with them. A thread is said to own the lock between the time it has acquired the lock and released the lock. As long as a thread owns a monitor lock, no other thread can acquire the same lock. The other thread will block when it attempts to acquire the lock.
  • When a thread releases the lock, a happens-before relationship is established between that action and any subsequent acquisition of the same lock.

所以监视器和锁不能进行比较,而是相辅相成。 Java 中的每个对象都与一个监视器相关联,线程可以锁定解锁

关于java - 在Java中,监视器和锁有什么区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49610644/

相关文章:

java - 在 Atlassian 插件中从当前用户获取凭证

java - Android Studio - 可绘制文件夹

perl - 如何在 Perl 中锁定文件?

java - 混合 volatile 和 synchronized 作为读写锁

java - java的线程概念中的synchronized

java - 同步有什么问题

java - 如何从java中的属性值中删除反斜杠

java - 如何使用传递给方法的参数为 catch 语句设置预期的异常类型?

locking - 取消搁置在 Perforce/P4 中独占 check out 的文件

database - 什么时候锁定数据库表?