Java中Semaphore(訊號量)的使用

來源:互聯網
上載者:User

標籤:dex   bar   exce   ace   ble   ber   多個   構造   tran   

Semaphore的作用:

在Java中,使用了synchronized關鍵字和Lock鎖實現了資源的並發存取控制,在同一時間只允許唯一了線程進入臨界區訪問資源(讀鎖除外),這樣子控制的主要目的是為瞭解決多個線程並發同一資源造成的資料不一致的問題。在另外一種情境下,一個資源有多個副本可供同時使用,比如印表機房有多個印表機、廁所有多個坑可供同時使用,這種情況下,Java提供了另外的並發存取控制--資源的多副本的並發存取控制,今天學習的訊號量Semaphore即是其中的一種。

Semaphore實現原理初探:

Semaphore是用來保護一個或者多個共用資源的訪問,Semaphore內部維護了一個計數器,其值為可以訪問的共用資源的個數。一個線程要訪問共用資源,先獲得訊號量,如果訊號量的計數器值大於1,意味著有共用資源可以訪問,則使其計數器值減去1,再訪問共用資源。

如果計數器值為0,線程進入休眠。當某個線程使用完共用資源後,釋放訊號量,並將訊號量內部的計數器加1,之前進入休眠的線程將被喚醒並再次試圖獲得訊號量。

 

Semaphore的使用:

Semaphore使用時需要先構建一個參數來指定共用資源的數量,Semaphore構造完成後即是擷取Semaphore、共用資源使用完畢後釋放Semaphore。

 

[java] view plain copy  print?
  1. Semaphore semaphore = new Semaphore(10,true);  
  2. semaphore.acquire();  
  3. //do something here  
  4. semaphore.release();  

下面的代碼就是類比控制商場廁所的並發使用:

 

import java.util.concurrent.*;import java.util.concurrent.locks.ReentrantLock;import java.util.*;import static net.mindview.util.Print.*;class ResourceManage {    private final Semaphore semaphore;    private boolean resourceArray[];    private final ReentrantLock lock;    public ResourceManage() {        this.resourceArray = new boolean[10];// 存放資源狀態        this.semaphore = new Semaphore(10, true);// 控制10個共用資源的使用,使用先進先出的公平模式進行共用;公平模式的訊號量,先來的先獲得訊號量        this.lock = new ReentrantLock(true);// 公平模式的鎖,先來的先選        for (int i = 0; i < 10; i++) {            resourceArray[i] = true;// 初始化為資源可用的情況        }    }    public void useResource(int userId) throws InterruptedException {        semaphore.acquire();        try {            // semaphore.acquire();            int id = getResourceId();// 佔到一個資源            System.out.print("userId:" + userId + "正在使用資源,資源id:" + id + "\n");            Thread.sleep(100);// do something,相當于于使用資源            resourceArray[id] = true;// 退出這個資源        } catch (InterruptedException e) {            e.printStackTrace();        } finally {            semaphore.release();// 釋放訊號量,計數器加1        }    }    private int getResourceId() {        int id = -1;        lock.lock();        try {            // lock.lock();//雖然使用了鎖控制同步,但由於只是簡單的一個數組遍曆,效率還是很高的,所以基本不影響效能。            for (int i = 0; i < 10; i++) {                if (resourceArray[i]) {                    resourceArray[i] = false;                    id = i;                    break;                }            }        } catch (Exception e) {            e.printStackTrace();        } finally {            lock.unlock();        }        return id;    }}public class ResourceUser implements Runnable {    private ResourceManage resourceManage;    private int userId;    public ResourceUser(ResourceManage resourceManage, int userId) {        this.resourceManage = resourceManage;        this.userId = userId;    }    public void run() {        System.out.print("userId:" + userId + "準備使用資源...\n");        try {            resourceManage.useResource(userId);        } catch (InterruptedException e) {            // TODO Auto-generated catch block            e.printStackTrace();        }        System.out.print("userId:" + userId + "使用資源完畢...\n");    }    public static void main(String[] args) {        ResourceManage resourceManage = new ResourceManage();        Thread[] threads = new Thread[100];        for (int i = 0; i < 100; i++) {            Thread thread = new Thread(new ResourceUser(resourceManage, i));// 建立多個資源使用者            threads[i] = thread;        }        for (int i = 0; i < 100; i++) {            Thread thread = threads[i];            try {                thread.start();// 啟動線程            } catch (Exception e) {                e.printStackTrace();            }        }    }
userId:2準備使用資源...userId:6準備使用資源...userId:4準備使用資源...userId:0準備使用資源...userId:3準備使用資源...userId:1準備使用資源...userId:8準備使用資源...userId:9準備使用資源...userId:10準備使用資源...userId:1正在使用資源,資源id:5userId:3正在使用資源,資源id:4userId:6正在使用資源,資源id:2userId:0正在使用資源,資源id:3userId:7準備使用資源...userId:2正在使用資源,資源id:0userId:4正在使用資源,資源id:1userId:5準備使用資源...userId:13準備使用資源...userId:7正在使用資源,資源id:9userId:12準備使用資源...userId:11準備使用資源...userId:10正在使用資源,資源id:8userId:15準備使用資源...userId:9正在使用資源,資源id:7userId:8正在使用資源,資源id:6userId:16準備使用資源...userId:14準備使用資源...userId:18準備使用資源...userId:17準備使用資源...userId:20準備使用資源...userId:19準備使用資源...userId:92準備使用資源...userId:93準備使用資源...userId:94準備使用資源...userId:95準備使用資源...userId:96準備使用資源...userId:97準備使用資源...userId:99準備使用資源...userId:98準備使用資源...userId:10使用資源完畢...userId:5正在使用資源,資源id:0userId:12正在使用資源,資源id:2userId:16正在使用資源,資源id:5userId:18正在使用資源,資源id:8userId:17正在使用資源,資源id:9userId:13正在使用資源,資源id:1userId:3使用資源完畢...userId:0使用資源完畢...userId:1使用資源完畢...userId:2使用資源完畢...userId:4使用資源完畢...userId:9使用資源完畢...userId:7使用資源完畢...userId:6使用資源完畢...

 

最後,Semaphore除了控制資源的多個副本的並發存取控制,也可以使用二進位訊號量來實作類別似synchronized關鍵字和Lock鎖的並發存取控制功能。

Java中Semaphore(訊號量)的使用

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.