2016-05-01 37 views
-2

我想知道爲什麼utils.concurrent有這麼複雜的源代碼。 這是我爲CountDownLatch提出的一些代碼,經過測試後,我期待在源代碼中找到類似的東西,但不是,它是非常複雜的。爲什麼CountDownLatch源代碼如此複雜?

我的實施有錯嗎?

public class CountDown { 

    private int count; 
    private Object lock; 

    public CountDown(int count) 
    { 
     lock = new Object(); 
     this.count = count; 
    } 
    //Just waits until it is notified by CountDown. Keeps waiting if not 0. 
    public void await() throws InterruptedException 
    { 
     synchronized (lock) { 
      while(count != 0) 
      { 
       lock.wait(); 
      } 
     } 
    } 
    //Decreases the count and notifies for await's lock. 
    public void countDown() 
    { 
     synchronized (lock) { 
      this.count--; 
      lock.notify();   
     } 
    } 
} 

而這裏的源代碼:Source Code CountDownLatch

+0

你的實現沒有那麼多的功能。如果您添加所有缺少的功能,您的實施將看起來幾乎相同。 –

+0

功能如?有非常複雜的方法,例如,私人類Sync中的循環是什麼? –

+0

哦哇...如果有人會倒下,至少請告訴我爲什麼請。 –

回答

1

CountDownLatch似乎只是一個包裝的AbstractQueuedSynchronizer。我認爲道格可能會注意到這一點,並決定採用這種方法,進一步導致其目前的設計。

通過私有Synch類,我在CountDownLatch中看到的一個重要功能是檢查中斷標誌。這在使用數十億次的通用庫代碼中非常重要。這意味着如果中斷標誌設置在某個地方之前,CountDownLatch會尊重它,並且不會進入任何等待狀態。這允許線程在應用程序結束並且所有線程都應該中斷時不掛起。當我關閉一個應用程序並被強制使用-9信號終止PID時,我看到這個問題很多。通常的罪魁禍首是壞的多線程代碼,它不能正確處理中斷,也不會檢查它。

+0

謝謝,我從來沒有想過這種可能性。 –

相關問題