当两个线程试图获取同一个对象的锁时,那些被认为决定锁定应该被移交给哪个线程的东西是什么.
最佳答案
根据Java documentation for notify():
原文链接:https://www.f2er.com/java/438014.htmlWakes 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:它有一个布尔标志来指定你想要强制公平.