State
- volatile修饰
- 同步状态
//同步状态
private volatile int state;
/**
* Returns the current value of synchronization state.
* This operation has memory semantics of a {@code volatile} read.
* @return current state value
*/
protected final int getState() {
return state;
}
/**
* Sets the value of synchronization state.
* This operation has memory semantics of a {@code volatile} write.
* @param newState the new state value
*/
protected final void setState(int newState) {
state = newState;
}
/**
* Atomically sets synchronization state to the given updated
* value if the current state value equals the expected value.
* This operation has memory semantics of a {@code volatile} read
* and write.
*
* @param expect the expected value
* @param update the new value
* @return {@code true} if successful. False return indicates that the actual
* value was not equal to the expected value.
*/
protected final boolean compareAndSetState(int expect, int update) {
// See below for intrinsics setup to support this
return unsafe.compareAndSwapInt(this, stateOffset, expect, update);
}
Node
SHARED && EXCLUSIVE
- 独占队列和共享队列是根据SHARED和EXCLUSIVE两个静态变量区分的
waitStatus
- 0,默认初始值
- CANCELLED,此节点由于超时或者中断被取消了,该状态不可以再次被修改为其他状态
- SIGNAL
- 表明后继节点在阻塞队列中,需要被唤醒,当前节点释放后(release)应该将后继节点从等待队列中移除(unpark)
- CONDITION,表明此节点处于条件等待状态(条件等待队列中),在调用Condition的await相关方法后会进入条件队列,并等待其他线程唤醒。
- PROPAGATE,传播
prev
- 前驱节点
next
- 后继节点
thread
- 等待队列中的线程,对应当前节点
nextWaiter
- 下一个等待节点,用于条件队列中
head
- 头结点
- 只有成功获取状态的节点才能成为头结点
tail
- 尾结点
spinForTimeoutThreshold
//设定的自旋时间
static final long spinForTimeoutThreshold = 1000L;
//在相关的抢夺锁过程中会有对超时时间的判断
if (shouldParkAfterFailedAcquire(p, node) &&
nanosTimeout > spinForTimeoutThreshold)
LockSupport.parkNanos(this, nanosTimeout);
ConditionObject
- 条件控制器,Condition接口实现类
/**
* Condition
*/
public interface Condition {
/**
* 挂起
*/
void await() throws InterruptedException;
void awaitUninterruptibly();
long awaitNanos(long nanosTimeout) throws InterruptedException;
boolean await(long time, TimeUnit unit) throws InterruptedException;
boolean awaitUntil(Date deadline) throws InterruptedException;
/**
* 唤醒
*/
void signal();
void signalAll();
}
/**
* ConditionObject
*/
public class ConditionObject implements Condition, java.io.Serializable {
private static final long serialVersionUID = 1173984872572414699L;
/** First node of condition queue. */
private transient Node firstWaiter;
/** Last node of condition queue. */
private transient Node lastWaiter;
/**
* Creates a new {@code ConditionObject} instance.
*/
public ConditionObject() { }
....
}
一般通过Sync对象去构造一个ConditionObject对象,用于Condition的相关操作
public Condition newCondition() {
return sync.newCondition();
}