一、概述
synchronized 是非公平锁。ReentrantLock 默认是非公平锁,但可设置为公平锁。
那线程通过Object.nofity()
和 Condition.signal()
被唤醒时是否是公平的呢?
先说结果,在Java 1.8 HotSpot
下,两者都是公平的。
查看Java文档:
void signal()
Wakes up one waiting thread.
If any threads are waiting on this condition then one is selected for waking up. That thread must then re-acquire the lock before returning from await.
Implementation Considerations
An implementation may (and typically does) require that the current thread hold the lock associated with this Condition when this method is called. Implementations must document this precondition and any actions taken if the lock is not held. Typically, an exception such as IllegalMonitorStateException will be thrown.
public final void 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.
The awakened thread will not be able to proceed until the current thread relinquishes the lock on this object. The awakened thread will compete in the usual manner with any other threads that might be actively competing to synchronize on this object; for example, the awakened thread enjoys no reliable privilege or disadvantage in being the next thread to lock this object.
This method should only be called by a thread that is the owner of this object's monitor. A thread becomes the owner of the object's monitor in one of three ways:
- By executing a synchronized instance method of that object.
- By executing the body of a synchronized statement that synchronizes on the object.
- For objects of type Class, by executing a synchronized static method of that class.
Only one thread at a time can own an object's monitor.
Object.nofity()
的文档明确说一个随机的线程将被唤醒,但具体情况将由实现者决定,因为Object.nofity()
是一个native方法。
Condition.signal()
的文档则说一个被选定的线程将被唤醒。
二、实验
2.1 对notify()
方法进行实验:
public class NotifyTest {
private final Object object = new Object();
private List<Integer> sleepList = new LinkedList<>