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();
}
}
一切工作正常,但它似乎並不是「最佳實踐」。可能有一些我沒有看到的瑕疵,或者可能有其他一些知名的做法來做我需要的事情?
Cebence,謝謝你的建議!你怎麼看待同步?看起來,TerminationObserver類中的每個方法都應該同步,但我不確定從屬算法的方法。 – Dmitry
任何將在線程間共享的內容都應該同步。在slave類的情況下,我認爲只有'terminate()'和'isTerminated()'。 – Cebence
好吧,我會做重構。謝謝! – Dmitry