publicvoidlock(){acquire(1);}protected final boolean tryAcquire(int acquires){
final Thread current = Thread.currentThread();
int c =getState();if(c ==0){//没有线程持有锁if(!hasQueuedPredecessors()&&//AQS队列该线程没有前驱节点compareAndSetState(0, acquires)){setExclusiveOwnerThread(current);//设置当前线程持有搜returntrue;}}//持有锁的就是当前线程elseif(current ==getExclusiveOwnerThread()){
int nextc = c + acquires;//增加锁次数if(nextc <0)thrownewError("Maximum lock count exceeded");setState(nextc);//更新AQS状态returntrue;}returnfalse;}
解锁
publicvoidunlock(){
sync.release(1);}public final boolean release(int arg){if(tryRelease(arg)){//解锁成功,即锁次数已归零
Node h = head;if(h !=null&& h.waitStatus !=0)unparkSuccessor(h);//唤醒AQS队列的后继节点returntrue;}returnfalse;}protected final boolean tryRelease(int releases){
int c =getState()- releases;//扣减锁次数if(Thread.currentThread()!=getExclusiveOwnerThread())thrownewIllegalMonitorStateException();//持有锁不是当前线程,不符合可重入锁规则,抛异常
boolean free =false;if(c ==0){//锁次数已归零,释放锁持有的配置
free =true;setExclusiveOwnerThread(null);}setState(c);return free;}
加锁时判断是否已加锁的为当前线程,如果是则加锁成功同时增加锁次数解锁时需要把加的锁次数扣减至0才算解锁成功分为公平和非公平锁加锁public void lock() { acquire(1);}protected final boolean tryAcquire(int acquires) { final Thread current = Thread.curren...