? ?
java semaphore是什么?讓我們一起來了解一下吧!
java semaphore是java程序中的一種鎖機制,叫做信號量。它的作用是操縱并且訪問特定資源的線程數量,允許規定數量的多個線程同時擁有一個信號量。
相關的方法有以下幾個:
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(); ????} }
以上就是小編今天的分享了,希望可以幫助到大家。