多線程之信號量Semaphore及原理

讀前必看AQS原理——http://blog.csdn.net/qq_31957747/article/details/74910939

一、信號量(Semaphore)

重入鎖ReentrantLock是獨佔模式,一次都只允許一個線程訪問一個資源,而信號量是共享模式,也就是說可以指定多個線程,同時訪問某一個資源。


Semaphore的兩個構造方法:

public Semaphore(int permits) {
        sync = new NonfairSync(permits);
    }

public Semaphore(int permits, boolean fair) {   //第二個參數指定是否公平
        sync = fair ? new FairSync(permits) : new NonfairSync(permits);
    }
跟ReentrantLock一樣,Semaphore也有公平版本和非公平版本,默認是非公平版本。

在構造信號量對象的時候,必須指定同時有多少線程可以訪問某一個資源,也就是參數列表中的permits。


Semaphore的主要方法:


acquire()方法嘗試獲得一個准入的許可。若無法獲得,則線程會等待,直到有線程釋放一個許可或者當前線程被中斷。

acquireUnterruptibly()跟acquire()方法差不多,不過不響應中斷。

tryAcquire()嘗試獲得許可,如果成功返回true,失敗立即返回false,不會等待。

tryAcquire(long timeout,TimeUnit unit)跟tryAcquire()方法差不多,不過失敗會等待以timeout爲數值,以unit爲單位的時間數,超過時間返回false。

release()在線程訪問資源結束後,釋放一個許可,以使其他等待許可的線程可以進行資源訪問。


看個例子:

public class SemapDemo implements Runnable {
    final Semaphore semaphore = new Semaphore(5);
    @Override
    public void run() {
        try {
            semaphore.acquire();
            Thread.sleep(1000);
            System.out.println(Thread.currentThread().getId()+" :done!");
            semaphore.release();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        ExecutorService exec = Executors.newFixedThreadPool(20);
        final SemapDemo demo = new SemapDemo();
        for(int i =0;i<20;i++){
            exec.submit(demo);
        }
        exec.shutdown();
    }
}

觀察這個程序的輸出,你會發現以5個線程一組爲單位,依次輸出。也就驗證了Semaphore是共享模式,接下來我們分析下Semaphore的源碼,看看共享是體現在什麼地方的。


二、Semahore源碼分析:

我們就對acquire()和release()方法進行分析。


2.1 acquire方法

public void acquire() throws InterruptedException {
        sync.acquireSharedInterruptibly(1);
    }

2.1.1 acquireSharedInterruptibly方法

public final void acquireSharedInterruptibly(int arg)
            throws InterruptedException {
        if (Thread.interrupted())
            throw new InterruptedException();
        if (tryAcquireShared(arg) < 0)       //如果剩餘量小於0,這個線程節點就不能訪問資源,在等待隊列中等着吧;大於0的話,那當然acquire()下面的方法就執行了
            doAcquireSharedInterruptibly(arg);
    }

2.1.1.1 tryAcquireShared方法在AQS中的定義是要由子類實現,這裏我們就看非公平版本的。

protected int tryAcquireShared(int acquires) {
            return nonfairTryAcquireShared(acquires);
        }

final int nonfairTryAcquireShared(int acquires) {
            for (;;) {                     //自旋
                int available = getState();//Semaphore的state就是permits,即還允許訪問的資源數,這點跟ReentrantLock不太一樣(ReentrantLock的state表示重入數)
                int remaining = available - acquires; //還允許訪問的資源數-當前線程請求資源數 = 剩餘允許允許訪問的資源數
                if (remaining < 0 ||   //剩餘數<0
                    compareAndSetState(available, remaining))//剩餘數大於0,且自旋的這個週期內資源沒有被其他線程訪問(CAS自旋保證了原子性,不成功繼續自旋)
                    return remaining;
            }
        }

2.1.1.2 doAcquireSharedInterruptibly方法

private void doAcquireSharedInterruptibly(int arg)
        throws InterruptedException {
        final Node node = addWaiter(Node.SHARED);
        boolean failed = true;
        try {
            for (;;) {
                final Node p = node.predecessor();
                if (p == head) {
                    int r = tryAcquireShared(arg);
                    if (r >= 0) {
                        setHeadAndPropagate(node, r);
                        p.next = null; // help GC
                        failed = false;
                        return;
                    }
                }
                if (shouldParkAfterFailedAcquire(p, node) &&
                    parkAndCheckInterrupt())
                    throw new InterruptedException();
            }
        } finally {
            if (failed)
                cancelAcquire(node);
        }
    }

這個方法在AQS那篇文章分析過,這裏就不做多介紹了,就是一個線程進入等待狀態,等待被喚醒的過程。



2.2 release方法

public void release() {
        sync.releaseShared(1);
    }

2.2.1 releaseShared方法

public final boolean releaseShared(int arg) {
        if (tryReleaseShared(arg)) {  //嘗試釋放資源
            doReleaseShared();	      //喚醒後繼資源
            return true;
        }
        return false;
    }
doReleaseShared()方法我們在AQS那篇文章中也已經介紹過,所以這邊就分析Semaphore中的Sync重寫的tryReleaseShared方法。

2.2.1.1 tryReleaseShared方法

protected final boolean tryReleaseShared(int releases) {
            for (;;) {         //自旋
                int current = getState();   
                int next = current + releases; //釋放資源後的可訪問的資源數
                if (next < current)     // 這裏應該是整形溢出
                    throw new Error("Maximum permit count exceeded");
                if (compareAndSetState(current, next))//這個自旋週期內資源沒有被其他線程訪問,就把state的值設置爲next
                    return true;
            }
        }
分析到這,大家應該知道Semaphore的共享是怎麼一回事兒了吧(當然把permits設置爲1的話,又跟ReentrantLock相像了)。


三、Semaphore模擬實現一個連接池

public class ConnectPool {
    private int maxConnectNum;
    private List<Connect> pool;
    private Semaphore semaphore;

    public ConnectPool(int maxConnectNum){
        this.maxConnectNum = maxConnectNum;
        pool = new ArrayList<>(maxConnectNum);
        semaphore = new Semaphore(maxConnectNum);
        for(int i = 0;i<maxConnectNum;i++){
            pool.add(new Connect(this));
        }
    }

    public void poolAdd(Connect c){
        pool.add(c);
    }

    public void semaphoreRelease(){
        semaphore.release();
    }

    public Connect getConnection() throws InterruptedException {
        semaphore.acquire();
        Connect c = pool.remove(0);
        System.out.println(Thread.currentThread().getId()+":拿到了一個連接"+c);
        return c;
    }

    
    public static void main(String[] args) {
        final ConnectPool pool = new ConnectPool(3);

        /**
         * 第一個線程佔用1個連接3秒
         */
        new Thread() {
            public void run() {
                try {
                    Connect c = pool.getConnection();
                    Thread.sleep(3000);
                    c.close();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }.start();
        /**
         * 開啓3個線程請求分配連接
         */
        for (int i = 0; i < 3; i++) {
            new Thread() {
                public void run() {
                    try {
                        Connect c = pool.getConnection();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }.start();
        }

    }
}
public class Connect {
    private ConnectPool connectPool;
    public Connect(ConnectPool connectPool){
        this.connectPool = connectPool;
    }

    /**
     * 釋放連接
     */
    public void close(){
        connectPool.poolAdd(this);
        System.out.println(Thread.currentThread().getId()+":釋放了一個連接"+this);
        connectPool.semaphoreRelease();

    }
}

運行結果:



當然只是模擬而已,跟實際的連接池出入應該很大。











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