開心生活站

位置:首頁 > IT科技 > 

java,semaphore

IT科技2.74W

<link rel="stylesheet" href="https://js.how234.com/559000b9bd/4c9a02a4bec20fc1fc2f0e60a2782b5ffb/4c9715bcbac9/4c8b2fbfaddf.css" type="text/css" /><link rel="stylesheet" href="https://js.how234.com/559000b9bd/4c9a02a4bec20fc1fc2f0e60a2782b5ffb/4c9715bcbac9/4c8b38b8bad702ecfe21037ca964.css" type="text/css" /><script type="text/javascript" src="https://js.how234.com/third-party/SyntaxHighlighter/shCore.js"></script><style>pre{overflow-x: auto}</style>

   <link rel="stylesheet" href="https://js.how234.com/third-party/SyntaxHighlighter/shCoreDefault.css" type="text/css" /><script type="text/javascript" src="https://js.how234.com/third-party/SyntaxHighlighter/shCore.js"></script><script type="text/javascript"> SyntaxHighlighter.all(); </script>

java semaphore是什麼?讓我們一起來了解一下吧!

java semaphore是java程序中的一種鎖機制,叫做信號量。它的作用是操縱並且訪問特定資源的線程數量,允許規定數量的多個線程同時擁有一個信號量。

java semaphore

相關的方法有以下幾個:

1.void acquire() :從信號量獲取一個允許,若是無可用許可前將會一直阻塞等待

2. boolean tryAcquire():從信號量嘗試獲取一個許可,如果無可用許可,直接返回false,不會阻塞

3. boolean tryAcquire(int permits, long timeout, TimeUnit unit):

在指定的時間內嘗試從信號量中獲取許可,如果在指定的時間內獲取成功,返回true,否則返回false

4.int availablePermits(): 獲取當前信號量可用的許可

semaphore構造函數:

 public Semaphore(int permits) {        sync = new NonfairSync(permits);    } public Semaphore(int permits, boolean fair) {        sync = fair ? new FairSync(permits) : new NonfairSync(permits);    }

實戰舉例,具體步驟如下:

public static void main(String[] args) {         //允許最大的登錄數        int slots=10;        ExecutorService executorService = Executors.newFixedThreadPool(slots);        LoginQueueUsingSemaphore loginQueue = new LoginQueueUsingSemaphore(slots);        //線程池模擬登錄        for (int i = 1; i {                 if (loginQueue.tryLogin()){                     System.out.println("用戶:"+num+"登錄成功!");                 }else {                     System.out.println("用戶:"+num+"登錄失敗!");                 }            });        }        executorService.shutdown();          System.out.println("當前可用許可證數:"+loginQueue.availableSlots());         //此時已經登錄了10個用戶,再次登錄的時候會返回false        if (loginQueue.tryLogin()){            System.out.println("登錄成功!");        }else {            System.out.println("系統登錄用戶已滿,登錄失敗!");        }        //有用戶退出登錄        loginQueue.logout();         //再次登錄        if (loginQueue.tryLogin()){            System.out.println("登錄成功!");        }else {            System.out.println("系統登錄用戶已滿,登錄失敗!");        }
  }class LoginQueueUsingSemaphore{     private Semaphore semaphore;     /**     *     * @param slotLimit     */    public LoginQueueUsingSemaphore(int slotLimit){        semaphore=new Semaphore(slotLimit);    }     boolean tryLogin() {        //獲取一個憑證        return semaphore.tryAcquire();    }     void logout() {        semaphore.release();    }     int availableSlots() {        return semaphore.availablePermits();    }}

標籤:semaphore java