stractQueuedSynchronizer在Java中并发

stractQueuedSynchronizer在Java中并发

本文介绍了AbstractQueuedSynchronizer在Java中并发的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在concurrent.locks包中使用的AbstractQueuedSynchronizer是什么?有人可以对其方法doAcquireInterruptably和parkAndCheckInterrupt?

What is AbstractQueuedSynchronizer in concurrent.locks package used for? Can someone throw some light on its methods doAcquireInterruptibly and parkAndCheckInterrupt ?

推荐答案

AbstractQueuedSynchronizer是同步结构的构建块,使用和实现)。

The AbstractQueuedSynchronizer is the building blocks for synchronization constructs that are used and implemented (at the very least) in the java.util.concurrency package.

例如,ReentrantLock委托给一个同步,它扩展了AbstractQueuedSynchronizer。如果你要写自己的锁,它可能看起来像这样

For instance, the ReentrantLock delegates to a Sync which extends AbstractQueuedSynchronizer. If you were to write your own lock it could look like this

public class MyLock extends AbstractQueuedSynchronizer implements Lock{
    @Override
    public void lock() {
        super.acquire(1);
    }
    @Override
    public void unlock() {
        if(Thread.currentThread() != super.getExclusiveOwnerThread())
            throw new IllegalMonitorStateException();
        super.release(1);
    }
}

所以这里MyLock类将继承低级功能的螺纹悬挂&排队到AQS,同时处理任何特殊的功能本身(例如,这个锁要求拥有锁的线程是释放它但是一个信号量没有)。

So here the MyLock class will inherit the low level functionality of thread suspension & queuing to the AQS while handling any special functionality itself (for instance this lock requires the thread owning the lock to be the one releasing it but a Semaphore does not).

注意:方法对类是私有的,因此实际的功能能够在不同版本或不同实现之间改变。在我解释的时候,默认提供的功能如下:

doAcquireInterruptably 成为此同步的独占所有者。它将永远这样做,直到线程被中断或成功获取。考虑一个线程试图进入同步块,线程将坐在那里,并且永远等待,直到它进入监视器(没有线程当前拥有或拥有线程存在监视器)。

doAcquireInterruptibly Will try to be the exclusive owner of this sync. It will do this for ever until the thread is interrupted or successfully acquires. Consider a thread trying to enter a synchronized block, the thread will sit there and wait forever until it enters the monitor (no thread currently owns or the owning thread exists the monitor). The advantage here is that the acquiring thread can be interrupted.

parkAndCheckInterrupt 只是一个方便的方法会暂停)一个线程,在复位中断状态时返回。

parkAndCheckInterrupt Just a convenience method that will suspend (park) a thread, return while resetting the interrupted status.

这篇关于AbstractQueuedSynchronizer在Java中并发的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-01 18:23