java - 对于 Java 类,内部锁实际上意味着什么?

标签 java multithreading concurrency synchronization

为了正确理解 Java 中并发的问题和解决方案,我正在阅读官方 Java 教程。在其中一个页面中,他们定义了内部锁和同步 link .在这个页面中,他们说:

As long as a thread owns an intrinsic lock, no other thread can acquire the same lock. The other thread will block when it attempts to acquire the lock.

另外,他们在同步方法中的锁部分提到:

When a thread invokes a synchronized method, it automatically acquires the intrinsic lock for that method's object and releases it when the method returns. The lock release occurs even if the return was caused by an uncaught exception.

对我来说,这意味着一旦我从其中一个线程调用同步方法,我将持有该线程的内在锁,并且因为

Intrinsic locks play a role in both aspects of synchronization: enforcing exclusive access to an object's state and establishing happens-before relationships that are essential to visibility.

另一个线程是否无法调用同一个类的另一个同步方法?如果是,那么拥有同步方法的整个目的就被打败了。不是吗?

最佳答案

似乎你有一个误解(不知道是否导致了错误的结论),没有人指出。无论如何,一个简短的回答:

Intrinsic Lock:就好像,JVM 中的每个对象都有一个内部锁。 synchronized 关键字尝试获取目标对象的锁。每当你 synchronized (a) { doSomething; ,实际发生的是

  1. 获取a中的锁
  2. 运行同步块(synchronized block)中的代码(doSomething)
  3. 释放a中的锁

我希望你知道

public synchronized void foo() {
  doSomething;
}

在概念上与

相同
public void foo() {
    synchronized(this) {
        doSomething;
    }
}

好吧,回到你的问题,恕我直言,最大的问题是:

For me this means that once I call a synchronized method from one of the threads, I will have hold of the intrinsic lock of the thread and since...

这是错误的。当您调用同步方法时,您不会获得线程的锁。

相反,线程 将拥有“拥有”该方法的对象 的内在锁。

例如在线程 1 中,您调用了 a.foo(),并假设 foo() 是同步的。线程 1 将获取引用对象 a 的内在锁。

同样,如果AClass.bar()被调用(并且bar是同步的静态方法),AClass的内在锁将获取类对象。

关于java - 对于 Java 类,内部锁实际上意味着什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38213467/

相关文章:

java - 线程优先级没有影响

ios - 核心数据对象的顺序改变,核心数据合并后上下文之间不同

java - 向上和向下绘制星星

java - 当数据库中存在更多行时,ResultSet 仅返回一行

ios - 虽然项目正在保存在核心数据中,但在重新启动之前无法查看它们

python停止多线程回显服务器

android - 如何通过触摸中断长时间的处理?

multithreading - 这种释放/获取语义的使用是否包含潜在的数据竞争?

java - 列表 WebElement 始终从下拉列表中选择第一个元素,但我想选择第四个元素

java - 我如何在java中替换{内部字符串