1. 定义
1、全称是 AbstractQueuedSynchronizer
2、阻塞式锁和相关的同步器工具的框架;
3、AQS用一个变量(volatile state) 属性来表示锁的状态,子类去维护这个状态
4、getState、compareAndSetState cas改变这个变量
5、独占模式是只有一个线程能够访问资源
6、而共享模式可以允许多个线程访问资源(读写锁)
7、内部维护了一个FIFO等待队列,类似于 synchronized关键字当中的 Monitor 的 EntryList
8、条件变量来实现等待、唤醒机制,支持多个条件变量,类似于 Monitor 的 WaitSet
9、内部维护了一个Thread exclusiveOwnerThread 来记录当前持有锁的那个线程
2. 功能
1、实现阻塞获取锁 acquire,拿不到锁就去阻塞,等待锁被释放再次获取锁
2、实现非阻塞尝试获取锁 tryAcquire,拿不到锁则直接放弃
3、实现获取锁超时机制
4、实现通过打断来取消
5、实现独占锁及共享锁
6、实现条件不满足的时候等待
3. 自定义实现AQS框架
3.1 继承AQS 实现其主要方法
package org.example;
import java.util.concurrent.locks.AbstractQueuedSynchronizer;
import java.util.concurrent.locks.Condition;
public class CustomSync extends AbstractQueuedSynchronizer {
public boolean tryAcquire(int acquires) {
if (compareAndSetState(0, acquires)) {
setExclusiveOwnerThread(Thread.currentThread());
return true;
}
return false;
}
public boolean tryRelease(int arg) {
if (getState() == 0) {
throw new IllegalMonitorStateException();
}
setExclusiveOwnerThread(null);
setState(0);
return true;
}
public boolean isHeldExclusively() {
return getState() == 1;
}
public Condition newCondition() {
return new ConditionObject();
}
}
3.2 实现Lock接口实现加锁解锁
package org.example;
import lombok.extern.slf4j.Slf4j;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
@Slf4j
public class CustomLock implements Lock {
CustomSync sync = new CustomSync();
@Override
public void lock() {
sync.acquire(1);
}
@Override
public void lockInterruptibly() throws InterruptedException {
sync.acquireInterruptibly(1);
}
@Override
public boolean tryLock() {
return sync.tryAcquire(1);
}
@Override
public boolean tryLock(long time, TimeUnit unit) throws InterruptedException {
return sync.tryAcquireNanos(1, unit.toNanos(time));
}
@Override
public void unlock() {
sync.release(1);
}
@Override
public Condition newCondition() {
return sync.newCondition();
}
public static void main(String[] args) throws InterruptedException {
CustomLock lock = new CustomLock();
new Thread(() -> {
lock.lock();
log.debug("t1 获取锁");
try {
TimeUnit.SECONDS.sleep(5);
} catch (InterruptedException e) {
e.printStackTrace();
}
lock.unlock();
}, "t1").start();
TimeUnit.SECONDS.sleep(1);
lock.lock();
log.debug("main 获取锁");
lock.unlock();
}
}
- 查看打印