【发布时间】:2016-08-03 07:09:51
【问题描述】:
只是好奇如何在崩溃后检查线程状态。到目前为止,我做了一些 System.exit(0) 或 (1) 但在我看来线程仍然活着并且可以运行 - 期待它被终止。这是我检查线程的测试代码
public static void main(String[] args) {
Runnable runnableJob = new JobThatImplementsRunnableJob();
Thread testThread = new Thread(runnableJob);
System.out.println("this is the testThread "+testThread.getState());
System.out.println("thread is alive " + testThread.isAlive());
testThread.start();
System.out.println("this is the testThread after starting"+testThread.getState());
System.out.println("thread is alive " + testThread.isAlive());
}
在可运行类中,我有意使用 System.exit(1) 或 (0)。我也确实让它抛出了一个错误,但仍然显示线程的 RUNNABLE 状态。
public class JobThatImplementsRunnableJob implements Runnable {
public void run() {
System.exit(1);
//System.exit(0);
//throws Error
}
}
下面是控制台输出
this is the testThread NEW
thread is alive false
this is the testThread after startingRUNNABLE
thread is alive true
希望以上信息足够,谢谢指教。
【问题讨论】:
-
我会在
JosThatImplementsRunnableJob中添加类似int i = 3/0;的东西,而不是System.exit(1) -
你有一个竞争条件阻止你做出任何结论,也就是说,你不知道也不可能知道首先会发生什么:主线程的最后一个 System.out,或者 System.out。您的单独线程的 exit()。
-
感谢 lino 和 GPI,线程睡眠和算术 ex 可以解决问题。
标签: java multithreading runnable jvm-crash