2011-12-17 89 views

回答

2

這不是一種理智的方式。只需編寫子線程以停止不再需要完成的工作。任何時候你都會問自己:「我怎樣才能從外部推動我的代碼,使它符合我想要的?」,停止並糾正自己。正確的問題是,「我怎樣才能編寫我的代碼來完成我真正希望它做的事情,這樣我就不必從外面推它了?」

+0

如果我對我今天的脾氣暴躁的帽子我會叫這個handwaving ......但我沒有,所以我不會)。如果OP問自己*我如何編寫自己的代碼來執行我真正想要的操作?*他的答案可能會是*我會編寫它來在一個線程找到正確答案*時停止所有其他線程。 – OldCurmudgeon 2011-12-17 21:00:41

+0

@Paul但是他沒有編寫另一個線程去做他想做的事情。他編碼他們做他*不希望他們做的工作,並推到其他一段代碼,使得第一部分代碼做他想做的事情。我的觀點很簡單 - 編寫所有的代碼來做你想做的事情,然後你不必擔心如何使它從別的地方做你想做的事。 – 2011-12-17 21:17:47

2

設置子級更新父級中的字段,如果它不爲空。讓孩子偶爾檢查該字段是否爲空。如果不是,他們應該停止。

這是否行得通?

2

我覺得完全可以接受子線程執行的其他子線程的終止。特別是如果子線程正在使用阻塞方法。你只需要一個家長stop方法可由兒童訪問。

喜歡的東西:

public interface Stopable { 
    public void stop(); 
} 

public class Child 
    extends Thread { 
    final Stopable parent; 
    boolean foundAnswer = false; 

    Child (Stopable parent) { 
    this.parent = parent; 
    } 

    public void run() { 
    try { 
     while (!isInterrupted()) { 
     // Do some work. 
     work(); 

     if (foundAnswer) { 
      // Stop everyone. 
      parent.stop(); 
     } 
     } 
    } catch (InterruptedException ie) { 
     // Just exit when interrupted. 
    } 
    } 

    private void work() throws InterruptedException { 
    while (!foundAnswer) { 
     // Do some work. 

     // Should we stop now? 
     checkForInterrupt(); 
    } 
    } 

    private void checkForInterrupt() throws InterruptedException { 
    if (isInterrupted()) { 
     throw new InterruptedException(); 
    } 
    } 

} 

public class Mainthread 
    implements Stopable { 
    ArrayList<Child> children = new ArrayList<Child>(); 

    public void go() { 
    // Spawn a number of child threads. 
    for (int i = 0; i < 5; i++) { 
     Child newChild = new Child(this); 
     children.add(newChild); 
     newChild.start(); 
    } 
    } 

    public void stop() { 
    // Interrupt/kill all child threads. 
    for (Child c : children) { 
     c.interrupt(); 
    } 
    } 
}