2013-04-13 61 views
1

有五種從屬算法和一種主算法。在每個主算法的迭代中,這五個從算法並行工作(它們都實現Runnable接口),並且當其中一個完成時,它會通知其他人,以便它們也終止,並且在所有這些算法完成後,主算法開始後處理。通知過程基於觀察者模式。每個從算法實現Terminatable接口,並且具有到一個TerminationObserver類的鏈路,它包含可運行的列表,並且具有這樣的方法:可終止線程觀察器

public synchronized void terminateAll() { 
    for (Terminatable terminatable : terminatables) { 
     if (!terminatable.isTerminated()) { 
      terminatable.terminate(); 
     } 
    } 
} 

每個從算法是一組迭代,所以終止通過設置terminated執行布爾變量爲true,這是停止迭代條件的一部分。這裏是從屬算法類的概述:

public class SlaveAlgorithm { 

    /** 
    * Process the algorithm. 
    */  
    public void run() { 
     try { 
      threadBarrier.await(); 

      while (!stopConditionMet()) { 
       performIteration() 
      } 

      // whether it is terminated by other algorithm or 
      // the stop conditions met 
      if (!isTerminated()) { 
       terminate(); 
       terminateOthers(); 
      } 

     } catch (Exception e) { 
     throw new RuntimeException(new AlgException(e)); 
     } 
    } 

    /** 
    * Tests whether the algorithms is terminated. 
    */ 
    public boolean isTerminated() { 
     return terminated; 
    } 

    /** 
    * Terminates the algorithm execution and 
    * causes other algorithms to terminate as well. 
    */ 
    public void terminate() { 
     terminated = true; 
    } 

    /** 
    * Removes the current algorithm form the termination observer's list 
    * and requests the termination of other algorithms, left in the termination observer. 
    */ 
    private void terminateOthers() { 
     terminationObserver.remove(this); // eliminate the already terminated process from the list 
     terminationObserver.terminateAll(); 
    } 
} 

一切工作正常,但它似乎並不是「最佳實踐」。可能有一些我沒有看到的瑕疵,或者可能有其他一些知名的做法來做我需要的事情?

回答

1

您應該將terminateOthers()的決策權改爲TerminationObserver而不是SlaveAlgorithm。你應該有這樣的事情:

public class SlaveAlgorithm { 
    public void run() { 
    try { 
     threadBarrier.await(); 

     while (!stopConditionMet() && !isTerminated()) { 
     performIteration() 
     } 
     done(); 
    } 
    catch ... 
    } 

    /** 
    * If not terminated notify observer the processing is done. 
    */ 
    private void done() { 
    if (!isTerminated()) { 
     terminationObserver.notifyDone(this) 
    } 
    } 

和觀察者應該做這樣的事情:

public class TerminationObserverImpl { 
    private void notifyDone(SlaveAlgorithm slave) { 
    remove(slave); // Remove it from the list. 
    terminateAll(); // Go through the list and terminate each slave. 
    } 
    ... 
+0

Cebence,謝謝你的建議!你怎麼看待同步?看起來,TerminationObserver類中的每個方法都應該同步,但我不確定從屬算法的方法。 – Dmitry

+0

任何將在線程間共享的內容都應該同步。在slave類的情況下,我認爲只有'terminate()'和'isTerminated()'。 – Cebence

+0

好吧,我會做重構。謝謝! – Dmitry