使用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/