一起读源码(一) Lock源码解析

Lock接口

public interface Lock {

	void lock();
	
	void lockInterruptibly() throws InterruptedException;
	
	boolean tryLock();
	
	boolean tryLock(long time, TimeUnit unit) throws InterruptedException;
	
	void unlock();
	
	Condition newCondition();
}

Lock实现类

ReentrantLock、WriteLock、ReadLock

lock获取锁

public void lock() {
	sync.lock();
}

abstract static class Sync extends AbstractQueuedSynchronizer {
	abstract void lock();
}

非公平锁

    static final class NonfairSync extends Sync {
        private static final long serialVersionUID = 7316153563782823691L;

        /**
         * Performs lock.  Try immediate barge, backing up to normal
         * acquire on failure.
         */
        final void lock() {
            if (compareAndSetState(0, 1))
	            //非公平锁if里面的条件就是插队,
	            //compareAndSetState(0, 1)
	            //意思就是插队看能不能拿到锁
	            //能拿到把当前线程设为sync的独占线程
                setExclusiveOwnerThread(Thread.currentThread());
            else
            	//正常请求锁
                acquire(1);
        }

        protected final boolean tryAcquire(int acquires) {
            return nonfairTryAcquire(acquires);
        }
    }

公平锁

  static final class FairSync extends Sync {
      private static final long serialVersionUID = -3000897897090466540L;

      final void lock() {
          acquire(1);
      }

      protected final boolean tryAcquire(int acquires) {
          final Thread current = Thread.currentThread();
          int c = getState();
          if (c == 0) {
              if (!hasQueuedPredecessors() &&
                  compareAndSetState(0, acquires)) {
                  setExclusiveOwnerThread(current);
                  return true;
              }
          }
          else if (current == getExclusiveOwnerThread()) {
              int nextc = c + acquires;
              if (nextc < 0)
                  throw new Error("Maximum lock count exceeded");
              setState(nextc);
              return true;
          }
          return false;
      }
  }

AQS

//AbstractQueuedSynchronizer.java
public final void acquire(int arg) {
        if (!tryAcquire(arg) &&
            acquireQueued(addWaiter(Node.EXCLUSIVE), arg))
            selfInterrupt();
    }

线程节点入队列

 private Node addWaiter(Node mode) {
        Node node = new Node(Thread.currentThread(), mode);
        // Try the fast path of enq; backup to full enq on failure
        Node pred = tail;
        if (pred != null) {
        //如果队列已经初始化了,直接把Node添加到队列尾端
            node.prev = pred;
            if (compareAndSetTail(pred, node)) {
                pred.next = node;
                return node;
            }
        }
        //如果队列没有初始化调用enq
        //enq做了两件事 初始化队列并把Node入队
        enq(node);
        return node;
    }
    
    private Node enq(final Node node) {
        for (;;) {//注意死循环
            Node t = tail;
            if (t == null) { //如果没有初始化尝试初始化
                if (compareAndSetHead(new Node()))
                    tail = head; //初始化成功接着循环,入队
                //走到这里说明初始化失败接着死循环初始化
            } else {
                //初始化成功 入队 并终止循环
                node.prev = t;
                if (compareAndSetTail(t, node)) {
                    t.next = node;
                    return t;
                }
            }
        }
    }

线程节点在AQS队列中获取锁

  final boolean acquireQueued(final Node node, int arg) {
        try {
            boolean interrupted = false;
            for (;;) {
            //又是死循环 只有获取到锁才会终止
            //获取当前线程所代表的node的前面一个节点
                final Node p = node.predecessor();
                //如果前面节点是头节点,尝试获取锁
                if (p == head && tryAcquire(arg)) {
                //如果当前线程获取锁成功,将当前节点设为头节点(再次强调下,头节点只是辅助的,真正的等待最久的节点是头节点的下一个节点),并且直接return掉
                    setHead(node);
                    p.next = null; // help GC
                    return interrupted;
                }
                //获取锁失败,判断是否需要阻塞线程
                if (shouldParkAfterFailedAcquire(p, node) &&
                    parkAndCheckInterrupt())
                    interrupted = true;
            }
        } catch (Throwable t) {
            cancelAcquire(node);
            throw t;
        }
    }

unlock释放锁

    public void unlock() {
        sync.release(1);
    }
public final boolean release(int arg) {
        //尝试释放锁
        if (tryRelease(arg)) {
            //释放成功,获取到AQS队列的头节点
            Node h = head;
            if (h != null && h.waitStatus != 0)
            //从头节点往队尾找到一个没有被取消的线程节点,唤醒它(只找一个不是所有的后面的节点)
                unparkSuccessor(h);
            return true;
        }
        return false;
}

 protected final boolean tryRelease(int releases) {
            int c = getState() - releases;
            //只有获取到了锁的线程才有资格调用该方法,完美的解释了没有获取锁的线程直接调用unlock()会报IllegalMonitorStateException
            if (Thread.currentThread() != getExclusiveOwnerThread())
                throw new IllegalMonitorStateException();
            boolean free = false;
            if (c == 0) {
                free = true;
                setExclusiveOwnerThread(null);
            }
            setState(c);
            return free;
        }

你可能感兴趣的:(JDK源码解析,并发,java,并发编程)