2013-04-13 88 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