Thread Stop Java

You are the creator of the thread and you must have full control over the thread, either for inactivation and then again activation or killing. For Thread Stop or killing a thread, stop() method of Thread class is used.
Following program illustrates on Thread Stop.
public class Demo extends Thread
{			        // d1 should be visible to run() method also
  static Demo d1;               // d1 must be static; else cannot be called from main()
  public void run()
    for(int i = 0; i < 10; i++)
        d1.stop();              // Thread stop () is not static method; must be called with an object
      System.out.println(i);    // prints 0 to 4 
  public static void main(String args[]) 
    d1 = new Demo(); 

Method signature of Thread Stop () method:

public final void stop() : Forces the thread to stop executing.

In the life cycle diagram, you have seen by calling stop() method from any state, the thread can be killed (stopped, brought to dead state and garbage collected).

The stop() method stops the execution of a running thread and removes from the waiting threads pool and garbage collected. It is possible from blocked state also.

In the above code, when i becomes 5, the running thread d1 is stopped and further iterations of the thread are cancelled.

Leave a Comment

Your email address will not be published.