我一直在寻找方法来杀死一个线程,看来这是最流行的方法替代方法杀死线程
public class UsingFlagToShutdownThread extends Thread {
private boolean running = true;
public void run() {
while (running) {
System.out.print(".");
System.out.flush();
try {
Thread.sleep(1000);
} catch (InterruptedException ex) {}
}
System.out.println("Shutting down thread");
}
public void shutdown() {
running = false;
}
public static void main(String[] args)
throws InterruptedException {
UsingFlagToShutdownThread t = new UsingFlagToShutdownThread();
t.start();
Thread.sleep(5000);
t.shutdown();
}
}
但是,如果在while循环中,我们产生另一个而它与填充另一个对象数据(比如正在运行和更新的gui),那么我们如何回调 - 特别是考虑到这种方法可能会被多次调用,所以我们有很多线程,而while(running)然后改变标志为一个会改变它为每个人?
谢谢
**没有一个解决方案,但最佳实践:**声明你的标志'running'为'volatile'。 – 2013-04-05 14:48:45
线程查杀的最佳方法是不要尝试。如果有任何方法可以设计应用程序,以便线程无需在操作系统在进程终止时杀死线程时被杀死,那么您应该这样做。 – 2013-04-05 14:56:53
但如果run方法有无限循环,即使关闭了gui线程正在将数据抽入,它仍然不会死亡:( – Biscuit128 2013-04-05 14:57:59