? ?
java semaphore是什么?讓我們一起來(lái)了解一下吧!
java semaphore是java程序中的一種鎖機(jī)制,叫做信號(hào)量。它的作用是操縱并且訪問(wèn)特定資源的線程數(shù)量,允許規(guī)定數(shù)量的多個(gè)線程同時(shí)擁有一個(gè)信號(hào)量。
相關(guān)的方法有以下幾個(gè):
1.void acquire() :從信號(hào)量獲取一個(gè)允許,若是無(wú)可用許可前將會(huì)一直阻塞等待
2.?boolean tryAcquire():從信號(hào)量嘗試獲取一個(gè)許可,如果無(wú)可用許可,直接返回false,不會(huì)阻塞
3.?boolean tryAcquire(int permits, long timeout, TimeUnit unit):
在指定的時(shí)間內(nèi)嘗試從信號(hào)量中獲取許可,如果在指定的時(shí)間內(nèi)獲取成功,返回true,否則返回false
4.int availablePermits(): 獲取當(dāng)前信號(hào)量可用的許可
semaphore構(gòu)造函數(shù):
?public?Semaphore(int?permits)?{ ????????sync?=?new?NonfairSync(permits); ????} ? public?Semaphore(int?permits,?boolean?fair)?{ ????????sync?=?fair???new?FairSync(permits)?:?new?NonfairSync(permits); ????}
實(shí)戰(zhàn)舉例,具體步驟如下:
public?static?void?main(String[]?args)?{ ? ????????//允許最大的登錄數(shù) ????????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("當(dāng)前可用許可證數(shù):"+loginQueue.availableSlots()); ? ????????//此時(shí)已經(jīng)登錄了10個(gè)用戶,再次登錄的時(shí)候會(huì)返回false ????????if?(loginQueue.tryLogin()){ ????????????System.out.println("登錄成功!"); ????????}else?{ ????????????System.out.println("系統(tǒng)登錄用戶已滿,登錄失敗!"); ????????} ????????//有用戶退出登錄 ????????loginQueue.logout(); ? ????????//再次登錄 ????????if?(loginQueue.tryLogin()){ ????????????System.out.println("登錄成功!"); ????????}else?{ ????????????System.out.println("系統(tǒng)登錄用戶已滿,登錄失敗!"); ????????}
??} class?LoginQueueUsingSemaphore{ ? ????private?Semaphore?semaphore; ? ????/** ?????* ?????*?@param?slotLimit ?????*/ ????public?LoginQueueUsingSemaphore(int?slotLimit){ ????????semaphore=new?Semaphore(slotLimit); ????} ? ????boolean?tryLogin()?{ ????????//獲取一個(gè)憑證 ????????return?semaphore.tryAcquire(); ????} ? ????void?logout()?{ ????????semaphore.release(); ????} ? ????int?availableSlots()?{ ????????return?semaphore.availablePermits(); ????} }
以上就是小編今天的分享了,希望可以幫助到大家。