作者热门文章
- Java 双重比较
- java - 比较器与 Apache BeanComparator
- Objective-C 完成 block 导致额外的方法调用?
- database - RESTful URI 是否应该公开数据库主键?
假设我们有多处理器机器和多线程应用程序。如果两个线程可以访问同步方法并且它们同时执行,哪个线程将获得锁?或者会发生什么?
谢谢
最佳答案
行为将是非确定性的(即,任一线程都可能获得锁),并且它可能因执行而异。这是因为它取决于特定的 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/
我是一名优秀的程序员,十分优秀!