模拟AQS中acquireQueued返回true的情况

本文详细解析了AQS中的acquireQueued方法,解释了该方法如何应用于ReentrantLock等类中的加锁过程,并通过示例展示了线程在等待获取锁期间被中断的行为。

AQS中有acquire方法:

    public final void acquire(int arg) {
        if (!tryAcquire(arg) &&
            acquireQueued(addWaiter(Node.EXCLUSIVE), arg))
            selfInterrupt();
    }

    final boolean acquireQueued(final Node node, int arg) {
        boolean failed = true;
        try {
            boolean interrupted = false;
            for (;;) {
                final Node p = node.predecessor();
                if (p == head && tryAcquire(arg)) {
                    setHead(node);
                    p.next = null; // help GC
                    failed = false;
                    return interrupted;
                }
                if (shouldParkAfterFailedAcquire(p, node) &&
                    parkAndCheckInterrupt())
                    interrupted = true;
            }
        } finally {
            if (failed)
                cancelAcquire(node);
        }
    }

上面的acquire方法用在ReentrantLock.FairSync,ReentrantLock.NonfairSync,ReentrantReadWriteLock.WriteLock,ThreadPoolExecutor.Worker类中的lock方法,加锁过程中如果失败就会进入队列(可能一开始就在队列)反复阻塞被唤醒直到成功获取锁,在此过程中,线程可能面临中断,acquireQueued方法返回值就是在等待的过程中是否被中断,该方法应用在await(),awaitNanos(long),awaitUnti(date),await(long,TimeUnit),awaitUninterruptibly()方法中用以判断中断状态

下面是通过代码模拟线程抢锁等待过程被中断

	public static void main(String[] args) throws InterruptedException {
		Lock lock = new ReentrantLock();
		new Thread(() -> {
			try {
				lock.lock();
				Thread.sleep(1000);
				System.out.println(Thread.currentThread().getName());
			} catch (InterruptedException e) {
				e.printStackTrace();
			} finally {
				lock.unlock();
			}
		}).start();
		Thread.sleep(100);


		Thread thread1 = new Thread(() -> {
			try {
				lock.lock();
				System.out.println(Thread.currentThread().getName() + "=" + Thread.currentThread().isInterrupted());
			} finally {
				lock.unlock();
			}
		});

		Thread thread2 = new Thread(() -> {
			lock.lock();
			try {
				System.out.println(Thread.currentThread().getName() + "=" + Thread.currentThread().isInterrupted());
			} finally {
				lock.unlock();
			}
		});
		thread1.start();
        Thread.sleep(1);
		thread2.start();
        Thread.sleep(1);
		thread2.interrupt();
	}

执行上面的代码,thread2直接进入断点interrupted=true

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值