子线程如何通知父线程终止所有其他的子线程的Java
答
这不是一种理智的方式。只需编写子线程以停止不再需要完成的工作。任何时候你都会问自己:“我怎样才能从外部推动我的代码,使它符合我想要的?”,停止并纠正自己。正确的问题是,“我怎样才能编写我的代码来完成我真正希望它做的事情,这样我就不必从外面推它了?”
答
设置子级更新父级中的字段,如果它不为空。让孩子偶尔检查该字段是否为空。如果不是,他们应该停止。
这是否行得通?
答
我觉得完全可以接受子线程执行的其他子线程的终止。特别是如果子线程正在使用阻塞方法。你只需要一个家长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();
}
}
}
如果我对我今天的脾气暴躁的帽子我会叫这个handwaving ......但我没有,所以我不会)。如果OP问自己*我如何编写自己的代码来执行我真正想要的操作?*他的答案可能会是*我会编写它来在一个线程找到正确答案*时停止所有其他线程。 – OldCurmudgeon 2011-12-17 21:00:41
@Paul但是他没有编写另一个线程去做他想做的事情。他编码他们做他*不希望他们做的工作,并推到其他一段代码,使得第一部分代码做他想做的事情。我的观点很简单 - 编写所有的代码来做你想做的事情,然后你不必担心如何使它从别的地方做你想做的事。 – 2011-12-17 21:17:47