ReentrantLock可重入鎖 ReentrantLock爲例實現細節 juc.Condition

aqs(AbstractQueuedSynchronizer)是一個用於構建鎖和同步器的框架
java.util.concurrent包中ReentrantLock、Semaphore、CountDownLatch、ReentrantReadWriteLock、SynchronousQueue都是通過aqs實現的

ReentrantLock爲例實現細節

ReentrantLock.lock()

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

ReentrantLock.NonfairSync.lock()

final void lock() {
    //第一個線程通過cas修改state狀態,0->1。修改成功返回true
    if (compareAndSetState(0, 1))
        setExclusiveOwnerThread(Thread.currentThread());    //記錄當前獨佔線程
    else
        acquire(1); //如果沒有獲取到鎖,調用AQS.acquire(1);
}

AQS.acquire(1);

public final void acquire(int arg) {
    //tryAcquire是aqs的模板方法,如果使用的非公平鎖ReentrantLock.NonfairSync會重寫這個方法
    if (!tryAcquire(arg) && acquireQueued(addWaiter(Node.EXCLUSIVE), arg))
        selfInterrupt();
}

ReentrantLock.NonfairSync.tryAcquire()

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

//此方法在NonfairSync父類Sync中
final boolean nonfairTryAcquire(int acquires) {
    final Thread current = Thread.currentThread();
    int c = getState();
    //如果狀態state被其他線程釋放後,修改爲0。那麼此時當前線程就可以直接拿到執行權,並返回true。AQS.acquire也就沒有必要在將線程放入鎖池中了。
    if (c == 0) {
        if (compareAndSetState(0, acquires)) {
            setExclusiveOwnerThread(current);
            return true;
        }
    } 
    //如果state<>0那麼說明鎖被其他線程佔有,還沒有釋放。但是要判斷一下是不是線程自己佔有的。如果是當前線程,那麼將state+1b,返回true。AQS.acquire也就沒有必要在將線程放入鎖池中了。
    else if (current == getExclusiveOwnerThread()) {
        int nextc = c + acquires;
        if (nextc < 0) // overflow
            //這個異常導致的原因待分析.............
            throw new Error("Maximum lock count exceeded"); 
        setState(nextc);
        return true;
    }
    //如果既沒有拿到執行權又不是當前線程重入,那麼就說明鎖已被其他線程佔用,返回false。繼續執行AQS.acquire方法中的 acquireQueued方法,將當前線程掛起放入鎖池中
    return false;
}

acquireQueued(addWaiter(Node.EXCLUSIVE), arg)

//線程沒有獲取到state鎖狀態,就需要放入到一個鎖池中(aqs中鏈表),然後在將這個線程掛起等待喚醒。
private Node addWaiter(Node mode) {
    Node node = new Node(Thread.currentThread(), mode);
    Node pred = tail;
    if (pred != null) {
        //如果aqs隊列存在尾節點,那麼就把新的node節點的前節點執行tail
        //         tail <- node 相當於
        node.prev = pred;
        //這一步cas操作是把aqs.tail 換成新加入鏈表的 node節點
        //         node(原tail對象) <- aqs.tail(新node節點對象)
        if (compareAndSetTail(pred, node)) {
            //這一步相當於把原tail對象的next指向 新node節點
            //     node(原tail對象).next -> aqs.tail(新node節點對象)
            pred.next = node;
            return node;
        }
    }
    //如果一共三個線程,那麼第一個線程不會進入到這個addWaiter方法,第二個線程會進入enq方法,將當前線程封裝的node節點放入隊列,head與tail相同。當第三個線程就會滿足if(pred != null)邏輯。
    enq(node); 
    return node;
}

//將剛加入鏈表中node的線程掛起等待喚醒
final boolean acquireQueued(final Node node, int arg) {
    boolean failed = true;
    try {
        boolean interrupted = false;
        
        for (;;) {
            //1.取出node的前置節點
            final Node p = node.predecessor();
            //2.然後判斷這個node的前置節點是不是aqs中的頭節點,如果是頭節點說明馬上就到當前這個node節點了,所以需要在嘗試獲取一下鎖狀態(state)。因爲在這個過程中很有可能aqs那個頭節點已經release了,並且鎖狀態就變成0了。
            if (p == head && tryAcquire(arg)) {
                //3.如果aqs頭節點釋放了那麼當前節點就不需要放入鎖池了再掛起了。將當前節點設置爲aqs頭節點,然後將aqs原頭結點設置成null,等GC。
                setHead(node);
                p.next = null; // help GC 
                
                failed = false;
                
                return interrupted;
            }
            //如果不符合第一個if判斷,再判斷是否需要掛起等待,如果需要阻塞線程。
            if (shouldParkAfterFailedAcquire(p, node) &&
                parkAndCheckInterrupt())
                interrupted = true;
        }
        
    } finally {
        if (failed)
            cancelAcquire(node);
    }
}

自己根據理解實現自定義的鎖工具

以下是根據aqs理解實現的,沒有經過大量驗證一定會存在無數bug,並且沒有考慮鎖重入,線程中斷,執行效率等等問題。

aqs的主要技術:自旋+volatile+CAS、LockSupport、鎖池

MyLock.java

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Random;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.locks.LockSupport;

public class MyLock {

    //鎖狀態
    AtomicInteger status = new AtomicInteger(0);
    
    //鎖池(所有被阻塞的線程)
    List<Thread> threadList = Collections.synchronizedList(new ArrayList<Thread>());
    
    //上鎖(獲取程序執行權)
    public void lock() {
        //偏向
        if(status.compareAndSet(0, 1)) {
            return;
        }
        //輕量
        for (int i = 0; i < 10; i++) {
            if(status.compareAndSet(0, 1)) {
                return;
            }
        }
        //重量
        while(true) {
            if(status.compareAndSet(0, 1)) {    //當線程被喚醒時,需要把狀態修改成佔用狀態
                return;
            }
            threadList.add(Thread.currentThread()); //並放入到鎖池中去,等待unLock操作隨機喚醒
            LockSupport.park(this); //當前線程阻塞
            
        }
        
    }
    
    //解鎖(其實是解除鎖池中線程的阻塞狀態)
    public void unLock() {
        status.getAndSet(0);    //將鎖狀態修改成未佔用狀態
        if(!threadList.isEmpty()) {
            //隨機從鎖池中恢復一個線程(模擬非公平鎖)
            LockSupport.unpark(threadList.remove(new Random().nextInt(threadList.size()))); 
        }
    }
}

測試類

public class Test3{
    
    static MyLock lock = new MyLock();
    
    static int count = 0;
    
    public static void main(String[] args) {
        
        CountDownLatch c = new CountDownLatch(10);
        
        for(int i=0; i<10; i++) {
            new Thread(()->{
                try {
                    TimeUnit.MILLISECONDS.sleep(1); //方便模擬出count是線程不安全的狀態值
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                count();
                c.countDown();
            }).start();
        }
        
        try {
            c.await();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        
        System.out.println(count);
    }
    
    public static void count() {
        lock.lock();
        
        for(int i=0; i<1000; i++) {
            count++;
        }
        
        lock.unLock();
    }
}

源碼中非公平鎖與公平鎖的區別在於tryAquire,非公平鎖對於新線程會先去競爭state狀態,如果競爭成功就可以執行,纔不管你鎖池裏有沒有等待的線程。如果競爭不到沒辦法進入鎖池排隊去。而公平鎖對於新線程會先去判斷鎖池裏有沒有等待的線程如果有,不好意思直接進鎖池排隊去。
線程一旦進去了鎖池那麼兩者就沒有區別了都排着隊一個一個的從頭部節點釋放出來。

如果非公平鎖能像自己實現的那樣能從鎖池中隨機釋放線程鎖去爭搶執行權,從全部線程來看是不是更不公平一些。

juc.Condition

線程之間協作,比如一個阻塞隊列。push方法是向隊列添加值,pull方法是拉取值。阻塞隊列就是如果隊列沒有內容pull方法阻塞直到隊列有值。那麼通過Condition的await、signal實現阻塞隊列。

import java.util.LinkedList;
import java.util.List;
import java.util.Scanner;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

public class ReentrantLock_main {

    //測試阻塞隊列
    public static void main(String[] args) {
        
        MyBlockingQueue<String> mb = new MyBlockingQueue<String>();
        
        //輸入線程
        new Thread(()->{
            Scanner s = new Scanner(System.in); //控制檯輸入內容
            while(true) {
                String str = s.nextLine();
                if("exit".equals(str)) {
                    System.exit(0); //退出
                } else {
                    System.out.println("輸入了:" + str);
                    mb.push(str);
                }
            }
        }).start();
    
        //接收線程A
        new Thread(()->{
            for(;;) {
                System.out.print("  乙pull " + mb.pull());
            }
        }).start();
        
        //接收線程B
        new Thread(()->{
            for(;;) {
                System.out.print("  丙pull " + mb.pull());
            }
        }).start();
    }

}

/**
 * 阻塞隊列
 * 
 * @author hdx
 * @date 2020年10月16日
 */
class MyBlockingQueue<T>{
    
    private List<T> list = new LinkedList<T>();
    
    ReentrantLock reentrantLock = new ReentrantLock();
    Condition conditionA = reentrantLock.newCondition();
    
    public void push(T t) {
        reentrantLock.lock();
        try {
            list.add(t);    //添加值
            conditionA.signal();    //通知await可以執行了
        } finally {
            reentrantLock.unlock();
        }
    }
    
    public T pull() {
        reentrantLock.lock();
        try {
            while(true) {
                if(list.size() > 0) {   //如果有值就返回值
                    return list.remove(0);
                } else {
                    try {
                        conditionA.await(); //如果沒有值就在此等着。
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        } finally {
            reentrantLock.unlock();
        }
    }
}

conditionA.await() 與 wait相同
conditionA.signal() 與notify相同
conditionA.signalAll()與notifyAll相同

juc.Condition實現細節

await方法分析

public final void await() throws InterruptedException {
            if (Thread.interrupted())
                throw new InterruptedException();
            Node node = addConditionWaiter();  //condition對象內部也有一個單向鏈表,向尾部增加節點。
            int savedState = fullyRelease(node);
            int interruptMode = 0;
            while (!isOnSyncQueue(node)) {
                LockSupport.park(this);
                if ((interruptMode = checkInterruptWhileWaiting(node)) != 0)
                    break;
            }
            if (acquireQueued(node, savedState) && interruptMode != THROW_IE)
                interruptMode = REINTERRUPT;
            if (node.nextWaiter != null) // clean up if cancelled
                unlinkCancelledWaiters();
            if (interruptMode != 0)
                reportInterruptAfterWait(interruptMode);
 }

signal方法分析


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章