-1

Following code is giving me NullPointerException.

class MT extends Thread{
    public void run(){
    }
}

public class ThreadGroupDemo{
    public static void main(String[] args) throws InterruptedException{
        MT t = new MT();
        t.start();
        Thread.sleep(5000);
        System.out.println(t.getName());
       //^^^^This line gives the thread name
        System.out.println(t.getThreadGroup().getName()); 
        //^^^^This line is giving me NullPointerException
    }
}

The last line of this code gives NullPointerException.

mp3001
  • 29
  • 4

1 Answers1

1

You called getThreadGroup. The api doc for this method says

Returns the thread group to which this thread belongs. This method returns null if this thread has died (been stopped).

The thread object itself is still around, it doesn’t get destroyed somehow. Once it has finished executing its run method and is no longer a GC root, then like any other object it doesn’t become eligible for garbage collection until nothing references it. You can check if a thread is dead by calling isAlive on it.

Starting a thread may take a little while. Removing the sleep from the main thread creates a race between the main thread printing and the new thread starting. It seems likely the main thread may print the information before the new thread gets started.

Nathan Hughes
  • 94,330
  • 19
  • 181
  • 276