package com.code.constructor.lock;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.AbstractQueuedSynchronizer;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
/**
* 基于aqs实现自定义锁
*/
public class MyLock1 implements Lock {
private Sync sync = new Sync();
private class Sync extends AbstractQueuedSynchronizer{
/**
* asq是基于state维护原子性的一致性的.
* 若当前有锁, 则将其他线程存入队列中.
*/
@Override
protected boolean tryAcquire(int arg) {
int state = getState();
if (state == 0) {
if (compareAndSetState(0, arg)) { // 保证了操作的原子性
setExclusiveOwnerThread(Thread.currentThread());
return true;
}
} else if (Thread.currentThread() == getExclusiveOwnerThread()) { // 重入锁
setState(state + 1);
return true;
}
return false;
}
@Override
protected boolean tryRelease(int arg) {
// 锁的获取与释放肯定是一一对应的
if (Thread.currentThread() != getExclusiveOwnerThread()) {
throw new RuntimeException("运行时异常");
}
int state = getState() - arg;
boolean flag = false;
if (state == 0) {
if (compareAndSetState(getState(), state)) {
flag = true;
setExclusiveOwnerThread(null);
}
}
return flag;
}
public Condition newCondition() {
return new ConditionObject();
}
}
@Override
public void lock() {
sync.tryAcquire(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.tryRelease(1);
}
@Override
public Condition newCondition() {
return sync.newCondition();
}
}
基于aqs,自定义lock对象
最新推荐文章于 2022-07-20 21:43:22 发布