Java中的AQS的底层方法和具体实现,请给出一个具体的实现代码
时间: 2023-03-15 21:13:44 浏览: 119
Java中AQS的底层方法主要有compareAndSet()、tryAcquireShared()和releaseShared()三个方法,具体实现如下:compareAndSet():
public final boolean compareAndSet(int expect, int update) {
return unsafe.compareAndSwapInt(this, stateOffset, expect, update);
}tryAcquireShared():
protected final int tryAcquireShared(int acquires) {
for (;;) {
int available = getState();
int remaining = available - acquires;
if (remaining < 0 ||
compareAndSetState(available, remaining))
return remaining;
}
}releaseShared():
protected final boolean tryReleaseShared(int releases) {
for (;;) {
int current = getState();
int next = current + releases;
if (next < current) // overflow
throw new Error("Maximum permit count exceeded");
if (compareAndSetState(current, next))
return true;
}
}
阅读全文