我有一个创建10个线程的程序,每个线程都有一个无限循环while循环。 我需要帮助来有效地实现一个关闭挂钩,它可以有效地停止所有的线程。因为我想做一个正常的关闭,所以每当一个线程发现停止标志变为TRUE时应该立即完成。优雅地关闭了多线程无限循环的程序
public class SampleGSH implements Runnable{
private static boolean stop = false;
public static void main(String[] args) {
for(int i = 0; i < 10;i++) {
Thread t = new Thread(new SampleGSH(), "name"+i);
t.start();
}
}
@Override
public void run() {
Runtime.getRuntime().addShutdownHook(new Thread("shutdown thread") {
public void run()
{
System.out.println("*******");
synchronized (this)
{
System.out.println("Turning switch off");
stop = true;
}
}
});
synchronized (this) {
while(!stop)
{
//Some logic which should not be killed abruptly once it starts running, a graceful shut down will not allow this code to start
}
}
}
}
任何帮助将得到真正的赞赏。
或者只是使用thread.interrupt()和thread.isInterrupted()方法,而不是@Gray的建议。 – 2013-05-05 19:00:51