加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Java > 正文

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

发布时间:2020-12-14 19:18:05 所属栏目:Java 来源:网络整理
导读:当两个线程试图获取同一个对象的锁时,那些被认为决定锁定应该被移交给哪个线程的东西是什么. 最佳答案 根据Java documentation for notify(): Wakes up a single thread that is waiting on this objects monitor. If any threads are waiting on this obje

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

最佳答案
根据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:它有一个布尔标志来指定你想要强制公平.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读