微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

java – 什么决定两个竞争线程中的哪一个获得锁定?

当两个线程试图获取一个对象的锁时,那些被认为决定锁定应该被移交给哪个线程的东西是什么.

最佳答案
根据Java documentation for notify()

Wakes up a single thread that is waiting on this object’s monitor. If
any threads are waiting on this object,one of them is chosen to be
awakened. The choice is arbitrary and occurs at the discretion of the
implementation.
A thread waits on an object’s monitor by calling one
of the wait methods.

因此,如果您使用synchronized(obj){},您基本上无法控制哪个线程将获取对obj的锁定,并且您无法做出任何假设.这取决于调度程序.

如果你想要公平(也就是说,获取锁的下一个线程是队列中的第一个),请看一下ReentrantLock:它有一个布尔标志来指定你想要强制公平.

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐