java多線程之并發(fā)工具類CountDownLatch,CyclicBarrier和Semaphore_第1頁
java多線程之并發(fā)工具類CountDownLatch,CyclicBarrier和Semaphore_第2頁
java多線程之并發(fā)工具類CountDownLatch,CyclicBarrier和Semaphore_第3頁
java多線程之并發(fā)工具類CountDownLatch,CyclicBarrier和Semaphore_第4頁
java多線程之并發(fā)工具類CountDownLatch,CyclicBarrier和Semaphore_第5頁
已閱讀5頁,還剩4頁未讀, 繼續(xù)免費閱讀

下載本文檔

版權說明:本文檔由用戶提供并上傳,收益歸屬內(nèi)容提供方,若內(nèi)容存在侵權,請進行舉報或認領

文檔簡介

第java多線程之并發(fā)工具類CountDownLatch,CyclicBarrier和SemaphorepublicSemaphore(intpermits,booleanfair){

sync=fairnewFairSync(permits):newNonfairSync(permits);

}

它支持傳入一個int類型的permits,一個布爾類型的fair,因此Semaphore也有公平模式與非公平模式。

*Synchronizationimplementationforsemaphore.UsesAQSstate

*torepresentpermits.Subclassedintofairandnonfair

*versions.

abstractstaticclassSyncextendsAbstractQueuedSynchronizer{

privatestaticfinallongserialVersionUID=1192457210091910933L;

Sync(intpermits){

setState(permits);

finalintgetPermits(){

returngetState();

finalintnonfairTryAcquireShared(intacquires){

for(;;){

intavailable=getState();

intremaining=available-acquires;

if(remaining0||

compareAndSetState(available,remaining))

returnremaining;

protectedfinalbooleantryReleaseShared(intreleases){

for(;;){

intcurrent=getState();

intnext=current+releases;

if(nextcurrent)//overflow

thrownewError("Maximumpermitcountexceeded");

if(compareAndSetState(current,next))

returntrue;

finalvoidreducePermits(intreductions){

for(;;){

intcurrent=getState();

intnext=current-reductions;

if(nextcurrent)//underflow

thrownewError("Permitcountunderflow");

if(compareAndSetState(current,next))

return;

finalintdrainPermits(){

for(;;){

intcurrent=getState();

if(current==0||compareAndSetState(current,0))

returncurrent;

}

第9行代碼可見Semaphore也是通過AQS的state來作為信號量的計數(shù)的

第12行getPermits()方法獲取當前的可用的信號量,即還有多少線程可以同時獲得信號量

第15行nonfairTryAcquireShared方法嘗試獲取共享鎖,邏輯就是直接將可用信號量減去該方法請求獲取的數(shù)量,更新state并返回該值。

第24行tryReleaseShared方法嘗試釋放共享鎖,邏輯就是直接將可用信號量加上該方法請求釋放的數(shù)量,更新state并返回。

再看下Semaphore的公平鎖

*Fairversion

staticfinalclassFairSyncextendsSync{

privatestaticfinallongserialVersionUID=2014338818796000944L;

FairSync(intpermits){

super(permits);

protectedinttryAcquireShared(intacquires){

for(;;){

if(hasQueuedPredecessors())

return-1;

intavailable=getState();

intremaining=available-acquires;

if(remaining0||

compareAndSetState(available,remaining))

returnremaining;

}

看嘗試獲取共享鎖的方法中,多了個if(hasQueuedPredecessors)的判斷,在java多線程6:ReentrantLock,

分析過hasQueuedPredecessors其實就是判斷當前等待隊列中是否存在等待線程,并判斷第一個等待的線程(head.next)是否是當前線程。

CyclicBarrier

CyclicBarrier的字面意思是可循環(huán)使用(Cyclic)的屏障(Barrier)。它要做的事情是,讓一組線程到達一個屏障(也可以叫同步點)時被阻塞,直到最后一個線程到達屏障時,屏障才會開門,所有被屏障攔截的線程才會繼續(xù)運行。

一組線程同時被喚醒,讓我們想到了ReentrantLock的Condition,它的signalAll方法可以喚醒await在同一個condition的所有線程。

下面我們還是從一個簡單的測試案例先了解下CyclicBarrier的用法

publicclassCyclicBarrierTestextendsThread{

privateCyclicBarriercb;

privateintsleepSecond;

publicCyclicBarrierTest(CyclicBarriercb,intsleepSecond){

this.cb=cb;

this.sleepSecond=sleepSecond;

publicvoidrun(){

try{

System.out.println(this.getName()+"開始,時間為"+System.currentTimeMillis());

Thread.sleep(sleepSecond*1000);

cb.await();

System.out.println(this.getName()+"結束,時間為"+System.currentTimeMillis());

}catch(Exceptione){

e.printStackTrace();

publicstaticvoidmain(String[]args){

Runnablerunnable=newRunnable(){

publicvoidrun(){

System.out.println("CyclicBarrier的barrierAction開始運行,時間為"+System.currentTimeMillis());

CyclicBarriercb=newCyclicBarrier(2,runnable);

CyclicBarrierTestcbt0=newCyclicBarrierTest(cb,3);

CyclicBarrierTestcbt1=newCyclicBarrierTest(cb,6);

cbt0.start();

cbt1.start();

}

執(zhí)行結果:

Thread-1開始,時間為1640069673534

Thread-0開始,時間為1640069673534

CyclicBarrier的barrierAction開始運行,時間為1640069679536

Thread-1結束,時間為1640069679536

Thread-0結束,時間為1640069679536

可以看到Thread-0和Thread-1同時運行,而自定義的線程barrierAction是在6000毫秒后開始執(zhí)行,說明Thread-0在await之后,等待了3000毫秒,和Thread-1一起繼續(xù)執(zhí)行的。

看下CyclicBarrier的一個更高級的構造函數(shù)

publicCyclicBarrier(intparties,RunnablebarrierAction){

if(parties=0)thrownewIllegalArgumentException();

this.parties=parties;

this.count=parties;

this.barrierCommand=barrierAction;

}

parties就是設定需要多少線程在屏障前等待,只有調(diào)用await方法的線程數(shù)達到才能喚醒所有的線程,還有注意因為使用CyclicBarrier的線程都會阻塞在await方法上,所以在線程池中使用CyclicBarrier時要特別小心,如果線程池的線程過少,那么就會發(fā)生死鎖。

RunnablebarrierAction用于在線程到達屏障時,優(yōu)先執(zhí)行barrierAction,方便處理更復雜的業(yè)務場景。

*Mainbarriercode,coveringthevariouspolicies.

privateintdowait(booleantimed,longnanos)

throwsInterruptedException,BrokenBarrierException,

TimeoutException{

finalReentrantLocklock=this.lock;

lock.lock();

try{

finalGenerationg=generation;

if(g.broken)

thrownewBrokenBarrierException();

if(Terrupted()){

breakBarrier();

thrownewInterruptedException();

intindex=--count;

if(index==0){//tripped

booleanranAction=false;

try{

finalRunnablecommand=barrierCommand;

if(command!=null)

command.run();

ranAction=true;

nextGeneration();

return0;

}finally{

if(!ranAction)

breakBarrier();

//loopuntiltripped,broken,interrupted,ortimedout

for(;;){

try{

if(!timed)

trip.await();

elseif(nanos0L)

nanos=trip.awaitNanos(nanos);

}catch(InterruptedExceptionie){

if(g==generation!g.broken){

breakBarrier();

throwie;

}else{

//We'reabouttofinishwaitingevenifwehadnot

//beeninterrupted,sothisinterruptisdeemedto

//"belong"tosubsequentexecution.

Thread.currentThread().interrupt();

if(g.broken)

thrownewBrokenBarrierException();

if(g!=generation)

returnindex;

if(timednanos=0L){

breakBarrier();

thrownewTimeoutException();

溫馨提示

  • 1. 本站所有資源如無特殊說明,都需要本地電腦安裝OFFICE2007和PDF閱讀器。圖紙軟件為CAD,CAXA,PROE,UG,SolidWorks等.壓縮文件請下載最新的WinRAR軟件解壓。
  • 2. 本站的文檔不包含任何第三方提供的附件圖紙等,如果需要附件,請聯(lián)系上傳者。文件的所有權益歸上傳用戶所有。
  • 3. 本站RAR壓縮包中若帶圖紙,網(wǎng)頁內(nèi)容里面會有圖紙預覽,若沒有圖紙預覽就沒有圖紙。
  • 4. 未經(jīng)權益所有人同意不得將文件中的內(nèi)容挪作商業(yè)或盈利用途。
  • 5. 人人文庫網(wǎng)僅提供信息存儲空間,僅對用戶上傳內(nèi)容的表現(xiàn)方式做保護處理,對用戶上傳分享的文檔內(nèi)容本身不做任何修改或編輯,并不能對任何下載內(nèi)容負責。
  • 6. 下載文件中如有侵權或不適當內(nèi)容,請與我們聯(lián)系,我們立即糾正。
  • 7. 本站不保證下載資源的準確性、安全性和完整性, 同時也不承擔用戶因使用這些下載資源對自己和他人造成任何形式的傷害或損失。

評論

0/150

提交評論