gpt4 book ai didi

Java:同步关键字不会阻塞不同线程上的对象

转载 作者:行者123 更新时间:2023-12-01 18:02:44 25 4
gpt4 key购买 nike

public class SynchronizeTest {

public synchronized void methodA() {
System.out.println("calling method a ...");
sleep(2000);
System.out.println("ending method a");
}

public void methodC() {
System.out.println("calling method C");
new Thread(new Runnable() {
@Override
public void run() {
methodA();
}
}).start();
sleep(100);
System.out.println("end method C");
}

public static void main(String[] args) {
new SynchronizeTest().methodC();
}


static void sleep(int millis) {
try {
Thread.sleep(millis);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}

首先,我猜是因为我同步方法A,这意味着整个对象将被锁定,直到该方法完成。所以答案应该是:

calling method C
calling method a
ending method a
ending method C

但结果是这样的:

calling method C
calling method A
ending method C
ending method A

这意味着 methodA 并不像我猜测的那样锁定对象。请告诉我原因。

最佳答案

当您在实例方法上使用 synchronized 关键字时,这意味着该对象上的方法同时只能由一个线程调用。

这并不意味着对所有对象的方法进行任何形式的锁定,即在该方法的调用期间可以调用其他实例方法 - 当您像正在做的那样异步调用它时也更容易。

由于您在 methodC 的线程中调用它,并且 methodA 中的 hibernate 时间比终止 methodC 之前的 hibernate 时间长得多>,你当前的输出很有可能每次都会发生。

这是相关的文档引用(请参阅第 here 页):

[...]making [...] methods synchronized has two effects:

  • First, it is not possible for two invocations of synchronized methods >on the same object to interleave. When one thread is executing a synchronized method for an object, all other threads that invoke synchronized methods for the same object block (suspend execution) until the first thread is done with the object.

  • Second, when a synchronized method exits, it automatically establishes > a happens-before relationship with any subsequent invocation of a synchronized method for the same object. This guarantees that changes to the state of the object are visible to all threads.

注意

您可能需要加入调用methodA的线程,以确保在打印methodC中的最后一条语句之前终止其执行。

关于Java:同步关键字不会阻塞不同线程上的对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39468160/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com