我有一个创建 10 个线程的程序,每个线程都有一个无限运行的 while 循环。我需要帮助来有效地实现一个可以有效地停止所有线程的 Shutdown 钩子。由于我想优雅地关闭每个线程,只要它发现停止标志变为 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
}
}
}
}
任何帮助将不胜感激。