只是好奇我可以检查崩溃后的线程状态。到目前为止,我做了一些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
我希望上面的信息就足够了,谢谢你的建议。
取代'System.exit(1)',我会添加类似'INT I = 3/0;'的'JosThatImplementsRunnableJob' – Lino
你有一个竞争条件阻止你做出任何结论,也就是说,你不知道什么会先发生:主线程的最后一个System.out或者sperate线程的System.exit()。 – GPI
感谢lino和GPI,线程睡眠和算术前处理技巧。 –