java中的同步功能是如何工作的?功能、工作、java

2023-09-07 16:14:10 作者:季末°不寂寞

自从我开始使用 Java 编程以来,我一直想知道这一点(大约一两年).在C语言中,我们必须知道正确避免线程之间死锁的不同方法,因此在同步方法之间有更多的选择.

Since I've started programming in Java I have been wondering this (about a year or two). In C, we must know the different method to correctly avoid deadlock between thread and thus there is much more choice between synchronization method.

那么 Java 呢?当我们同步时,它如何避免使线程陷入死锁情况?它在内部是如何工作的?是否因为我们在比 C(或 C++)更高的级别上同步而避免了死锁?有没有关于 java 中的死锁和同步的文档?

So what about Java? When we synchronize, how does it avoid putting thread in deadlock situation? How does it work internally? Does the deadlock are avoided because we synchronized on higher level than in C ( or C++)? Any documentation about deadlock and synchronization in java?

推荐答案

在底层使用两个操作码 monitorentermonitorexit 在字节码级别获取/在 JVM 全局级别释放对象引用上的锁.我强烈建议您阅读 Java虚拟机如何进行线程同步.

Under the hood it is using two opcodes monitorenter and monitorexit at the byte code level which acquire/release locks on an object reference at a JVM global level. I highly recommend you read How the Java virtual machine performs thread synchronization.