Java5 多線程(四)–Semaphore實現號誌

來源:互聯網
上載者:User
  Semaphore可以維護當前訪問自身的線程個數,並提供了同步機制,使用Semaphore可以控制同時訪問資源的線程數,例如,實現一個檔案允許的並發訪問數.        Semaphore實現的功能就類似廁所一共有5個茅坑(new Semaphore(5)),加入有10個人(10個線程)要上廁所,那麼同時只能有5個人能夠佔用,當佔用的5個人任何一個讓開後(release()方法),其中等待的另外5個人中又有一個可以佔用了(acquire()方法).        另外等待的5個人可以是隨機擷取優先機會,也可以是按照先來後到的順序擷取機會,這取決於構造方法傳入的參數選項.public Semaphore(int permits, boolean fair)        單個訊號量的Semaphore對象可以實現互斥鎖的功能,並且可以是由一個線程獲得鎖,再由另外一個線程釋放鎖,也就是一個線程可以去釋放鎖,儘管他沒有得到permit,這可以應用死結恢複的一些場合.public class SemaphoreTest {

    public static void main(String[] args) {        ExecutorService service = Executors.newCachedThreadPool();        final Semaphore sp = new Semaphore(3,true);        for (int i = 0; i < 10; i++) {            Runnable runnable = new Runnable() {                public void run() {                    try {                        sp.acquire();                    } catch (InterruptedException e1) {                        e1.printStackTrace();                    }                    System.out.println("線程" + Thread.currentThread().getName()                            + "進入,當前已有" + (3 - sp.availablePermits()) + "個並發");                    try {                        Thread.sleep((long) (Math.random() * 10000));                    } catch (InterruptedException e) {                        e.printStackTrace();                    }                    System.out.println("線程" + Thread.currentThread().getName()                            + "即將離開");                    sp.release();                    // 下面代碼有時候執行不準確,因為其沒有和上面的代碼合成原子單元                    System.out.println("線程" + Thread.currentThread().getName()                            + "已離開,當前已有" + (3 - sp.availablePermits()) + "個並發");                }            };            service.execute(runnable);        }

    }

轉載請註明出處: http://blog.csdn.net/johnny901114/article/details/8695717
相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.