gpt4 book ai didi

java - 为什么没有僵局

转载 作者:行者123 更新时间:2023-12-03 12:59:25 25 4
gpt4 key购买 nike

public class UThread implements Runnable {
@Override
public void run() {
synchronized (this) {
System.out.println("this is first");
synchronized (this) {
System.out.println("this is second");
}
}

}
}


public class main {
public static void main(String str[]) {
UThread uThread = new UThread();
Thread t = new Thread(uThread);
t.start();
}
}

执行代码时,它正在打印:

this is first
this is second

为什么没有僵局?如果代码试图锁定已被自身占用的 this

最佳答案

这是设计使然。 Java的monitorenter指令位于synchronized关键字后的大括号处,有意检查对象是否已被当前线程阻塞,如果是,则增加阻塞计数器并使用户代码继续执行。synchronized语句的右花括号表示monitorexit指令,该指令可减少阻塞计数器,如果计数器变为零,则释放监视器并允许其他线程进入synchronized语句。

关于java - 为什么没有僵局,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45772363/

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