簡體   English   中英

了解信號量......

[英]Understanding Semaphores…

我在這里有一個代碼,用於解釋信號量是如何工作的。無論我怎么努力,我都不理解下面的行,並且在那里如何調用信號量調用。

基本上代碼試圖模擬許多連接...

import java.util.concurrent.Semaphore;

public class Connection {

    private static Connection instance = new Connection();

    private Semaphore sem = new Semaphore(10, true);

    private int connections = 0;

    private Connection() {

    }

    public static Connection getInstance() {
        return instance;
    }

    public void connect() {
        try {
            sem.acquire();
        } catch (InterruptedException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }

        try {
            doConnect();
        } finally {

            sem.release();
        }
    }

    public void doConnect() {

        synchronized (this) {
            connections++;
            System.out.println("Current connections: " + connections);
        }

        try {
            Thread.sleep(2000);
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        synchronized (this) {
            connections--;
        }

    }
}

主類文件..

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;


public class App {

    public static void main(String[] args) throws Exception {

        ExecutorService executor = Executors.newCachedThreadPool();

        for(int i=0; i < 200; i++) {
            executor.submit(new Runnable() {
                public void run() {
                    Connection.getInstance().connect();
                }
            });
        }

        executor.shutdown();

        executor.awaitTermination(1, TimeUnit.DAYS);
    }

}

我不了解跑步部分

public void run() {
    Connection.getInstance().connect();
}

我們如何從上面調用connect方法? 在我的判斷中,當調用新線程時,連接輸出應始終為1。 令人驚訝,但從未發生過。

信號量用於獲取鎖,並執行一些代碼然后最終釋放鎖。

在你的代碼中也發生了同樣的事情。

  1. sem.acquire(); 將鎖定。
  2. doConnect(); //在這里寫你的代碼
  3. sem.release(); 釋放鎖。

有關詳細信息,請參閱

我會試着解釋一下那里發生了什么。 由於您將其提交到線程池,因此以下代碼在每個單獨的線程中運行:

public void run() {
    Connection.getInstance().connect();
}

Connection.getInstance()在這里返回一個單例(一個對象Connection的單個實例,它在線程之間共享,更多: 在Java中實現單例模式的有效方法是什么? )。 這個單例包含一個信號量,它也是單個信號並在線程之間共享。 因此,在這種情況下,此技術的全部目的是在多個線程之間共享信號量。

connect()會發生什么:

public void connect() {
    try {
        // this acquires a single permit for a shared semaphore,
        // so no more than 10 threads (the result of new Semaphore(10, true)) 
        // will enter the critical section below simultaneously
        sem.acquire();
    } catch (InterruptedException e1) {
        e1.printStackTrace();
    }

    try {
        // the critical section, at this point there will be 10 threads at max
        // this is the purpose of the semaphore
        doConnect();
    } finally {
        // returns the permit acquired, so that a one more thread may 
        // enter the critical section
        sem.release();
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM