Search code examples
javamultithreadingrunnablejvm-crash

How to crash a thread or intentionally hung the thread?


Just curious on how I can check a thread status after crashes. so far, i did some System.exit(0) or (1) but it seemed to me the thread is still alive and runnable - was expecting for it to be terminated. Here's my test code on checking the thread

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());

}

and inside the runnable class, I intendedly use System.exit(1) or (0). I too did make it throw an Error but still showing RUNNABLE state of the thread.

public class JobThatImplementsRunnableJob implements Runnable {
    public void run() {
        System.exit(1);
        //System.exit(0);
        //throws Error
    }

}

Below is the console output

this is the testThread NEW
thread is alive false
this is the testThread after startingRUNNABLE
thread is alive true

I hope the info above is sufficient, thanks for advices.


Solution

  • The thread is actually alive when the last two Sysouts of the main are run. You need to put a sleep in the Main thread. May be 5 seconds.