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

相关文章

最近看了一下学习资料,感觉进制转换其实还是挺有意思的,尤...
/*HashSet 基本操作 * --set:元素是无序的,存入和取出顺序不...
/*list 基本操作 * * List a=new List(); * 增 * a.add(inde...
/* * 内部类 * */ 1 class OutClass{ 2 //定义外部类的成员变...
集合的操作Iterator、Collection、Set和HashSet关系Iterator...
接口中常量的修饰关键字:public,static,final(常量)函数...