gpt4 book ai didi

java - 哪个线程将获得锁?

转载 作者:搜寻专家 更新时间:2023-10-31 08:29:58 24 4
gpt4 key购买 nike

假设我们有多处理器机器和多线程应用程序。如果两个线程可以访问同步方法并且它们同时执行,哪个线程将获得锁?或者会发生什么?

谢谢

最佳答案

行为将是非确定性的(即,任一线程都可能获得锁),并且它可能因执行而异。这是因为它取决于特定的 JVM 实现和线程的特定调度。

根据这篇文章,JVM 规范对公平性没有任何限制:

Fairness
The Java memory model does not specify any fairness requirement for threads or preemptive multi-threading. A thread can refuse to surrender the CPU to another thread and throw the system into deadlock. The rules for fairness to other threads are defined by the individual JVM implementations.

也就是说,除非您小心地同步您的程序,否则理论上一个线程可能会被调度程序饿死。

关于java - 哪个线程将获得锁?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3952804/

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