十八、condition之awaitNanos方法

220 阅读1分钟

awaitNanos方法

awaitNanos方法执行流程:

  • 判断是否中断,如果被中断就抛异常
  • 将线程放入condition链表中,并且释放锁资源
  • 计算线程挂起的终止时间
  • 判断线程是否在AQS链表中,如果不在,判断线程挂起时间是否满足>=1000纳秒
  • 如果不满足则将线程放入AQS链表中,如果满足则继续挂起
public final long awaitNanos(long nanosTimeout)
		throws InterruptedException {
	if (Thread.interrupted())
		throw new InterruptedException();
	// 将线程放入condition链表中
	Node node = addConditionWaiter();
	// 释放锁资源
	int savedState = fullyRelease(node);
	// 计算出线程挂起的终止时间
	final long deadline = System.nanoTime() + nanosTimeout;
	int interruptMode = 0;
	while (!isOnSyncQueue(node)) {
		if (nanosTimeout <= 0L) {
			// 如果挂起时间<=0,直接放入AQS队列中
			transferAfterCancelledWait(node);
			break;
		}
		if (nanosTimeout >= spinForTimeoutThreshold)
			// 如果挂起时间>=1000纳秒,挂起线程
			LockSupport.parkNanos(this, nanosTimeout);
		if ((interruptMode = checkInterruptWhileWaiting(node)) != 0)
			// 如果线程被中断唤醒,那就被唤醒
			break;
		// 线程被signal唤醒,计算剩余挂起时间,如果>=1000纳秒,继续挂起
		nanosTimeout = deadline - System.nanoTime();
	}
	if (acquireQueued(node, savedState) && interruptMode != THROW_IE)
		interruptMode = REINTERRUPT;
	if (node.nextWaiter != null)
		unlinkCancelledWaiters();
	if (interruptMode != 0)
		reportInterruptAfterWait(interruptMode);
	return deadline - System.nanoTime();
}