gpt4 book ai didi

java - 在静态对象上同步

转载 作者:行者123 更新时间:2023-11-30 09:08:22 25 4
gpt4 key购买 nike

我真的对同步的实际工作方式感到困惑。我有以下代码:

public class FunTest {
static FunTest test;

public void method() {
synchronized (test) {
if (Thread.currentThread().getName() == "Random1") {
try {
wait();
} catch (InterruptedException ex) {
ex.printStackTrace();
}
} else {
notify();
}
}
}

public static void main(String[] args) {
test = new FunTest();
final FunTest t0 = new FunTest();
Thread t1 = new Thread(new Runnable() {
public void run() {
t0.method();
}
});
Thread t3 = new Thread(new Runnable() {
public void run() {
t0.method();
}
});
t1.setName("Random1");
t3.setName("Random2");
t1.start();
t3.start();
}
}

代码在运行时抛出 IllegalMonitorStateException。我不明白为什么会这样。这样获取锁是不可能的吗?

如果我在同步块(synchronized block)中将 test 替换为 this,它仍然可以正常工作。为什么会这样?

最佳答案

您在 test 上打开了一个监视器 block ,但是您将 wait()notify() 应用到 this.

关于java - 在静态对象上同步,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23559249/

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