publicvoidlock() { sync.lock(); } /** * Performs {@link Lock#lock}. The main reason for subclassing * is to allow fast path for nonfair version. */ abstractvoidlock();
首先看NonfairSync
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
/** * Performs lock. Try immediate barge, backing up to normal * acquire on failure. * 执行获取锁的操作,尝试获取锁,如果失败的话,进入同步队列等待。 */ finalvoidlock() { //CAS尝试获取锁。 if (compareAndSetState(0, 1)) //如果获取锁成功的话,将自己放在当前持有锁的线程位置。 setExclusiveOwnerThread(Thread.currentThread()); else //获取锁失败,直接入同步队列,这块就和公平锁一样了。 acquire(1); }
/** * Fair version of tryAcquire. Don't grant access unless * recursive call or no waiters or is first. * 公平版本的获取锁, */ protectedfinalbooleantryAcquire(int acquires) { //获取当前线程 finalThreadcurrent= Thread.currentThread(); //获取当前锁的状态,即AQS中的state属性 intc= getState(); //c==0即锁没有被占用 if (c == 0) {