我有以下代码:
public static void main(String[] args) throws InterruptedException {
int [] intArray = new int[500];
SomeThread t1 = new SomeThread(intArray,0,99,1);
SomeThread t2 = new SomeThread(intArray,100,200,2);
t1.run();
System.exit(0);
Thread hook = new Thread(){
public void run(){
if(!t1.isReady){
t1.run();
}
else if(!t2.isReady){
System.out.println("Code reached here ------");
t2.run();
}
}
};
Runtime.getRuntime().addShutdownHook(hook);
}
基本上我有一个由两个不同线程操作的数组。线程内部有一个 boolean 变量 isReady
,用于检查线程是否已正确完成其工作。我故意没有启动第二个线程,只是为了检查它是否会在 System.exit() 之后执行,但代码永远不会到达那里。我只想在关闭 JVM 之前运行第二个线程。我还放置了 System.exit() 只是为了测试应用程序是否会在关闭之前执行某些操作。
更新:问题是为什么代码永远不会到达第二个 if 语句,我检查了 isReady 变量是否为 false:/
最佳答案
您必须在调用System.exit()
之前注册 Hook 。按照现在编写代码的方式,设置 Hook 的部分永远不会被实际评估。
关于Java addShutdownHook 方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38396114/