How to Stop Thread in Java with Example

How to stop a Thread in Java | A thread in Java program will terminate ( or move to dead state) automatically when it comes out of run() method.

But if we want to stop a thread from running or runnable state, we will need to calling stop() method of Thread class.  The stop() method is generally used when we desire premature death of a thread.

The general syntax for calling stop method is as follows:

static void stop()

Since the stop() method is static in nature, therefore, it can be called by using Thread class name. When the stop() method is called on a thread, it causes the thread to move to the dead state. Look at the below figure.How to stop a thread in Java

As you can observe in the above figure, a thread is terminated when it moves into the dead state either from running or runnable state. If any other thread does not interrupt a thread, it terminates normally.

If a running thread is interrupted then it throws InterruptedException and is terminated. After a thread is gone into the dead state, it cannot be made alive even after the calling of start() method.

If we will try to call start() method on a dead thread, start() method throws an exception named IllegalThreadStateException.

How to stop Running Thread in Java?


Let’s take an example program where we will kill a running thread by calling stop() method of Thread class.

Program source code 1:

public class Kill extends Thread
{
// Declare a static variable to of type Thread.
   static Thread t;	

public void run()
{
 System.out.println("Thread is running");	
 t.stop(); // Calling stop() method on Kill Thread.
 System.out.println("Learn Java step by step");
}
public static void main(String[] args) 
{
 Kill k = new Kill();
  t = new Thread(k);
 t.start(); // Calling start() method.
 }
}
Output:
       Thread is running

Explanation:

In the preceding example program, when stop() method is called on a running thread, the next statement is not executed and thread moved into the dead state and is terminated.

How to stop Runnable Thread in Java?


Let’s create a program where we will stop runnable thread in Java. Look at the following source code.

Program source code 2:

public class Thread1 implements Runnable
{
public void run()
{
 System.out.println("First child thread");
 }
}
public class Thread2 implements Runnable
{
static Thread t2;	
public void run()
{
for(int i = 0; i <= 10; i ++)
{
 System.out.println("Second child thread: " +i);	 
 if(i==5)
 {	 
  t2.stop(); // Calling stop() method to kill running thread.
 }
 }
 }
}
public class MyThreadClass 
{
public static void main(String[] args) 
{
Thread1 th1 = new Thread1();
Thread2 th2 = new Thread2();

Thread t1 = new Thread(th1);
Thread t2 = new Thread(th2);

t1.start();
t1.stop(); // Calling stop() method to kill runnable thread.
t2.start();
 }
}
Output:
       Second child thread: 0
       Second child thread: 1
       Second child thread: 2
       Second child thread: 3
       Second child thread: 4
       Second child thread: 5
       Exception in thread "Thread-1" java.lang.NullPointerException
	at threadProgram.Thread2.run(Thread2.java:13)
	at java.lang.Thread.run(Unknown Source)

Explanation:

In this example program, when we called start() method of Thread class on Thread1, the Thread1 moves into the runnable state from newborn state. After Thread1 is moved into the runnable state, it moves into the dead state due to the calling of stop() method on this thread.


Hence, Thread1 is terminated in a runnable state. Similarly, Thread2 is terminated in a running state due to the calling of stop() method after the successful completion of the 4th loop.

Can a thread is again alive when it goes into dead state?


No, when a thread is terminated or moves into dead state, it cannot alive again. If we try to it by calling start() method, we will get an IllegalThreadStateException exception. Let’s take an example program based on it.

Program source code 3:

public class Thread1 implements Runnable
{
static Thread t1;	
public void run()
{
 System.out.println("Thread is running");
 int i = 0;
while(i < 10)
{
 System.out.println("i: " +i);
 if(i == 5)	
  t1.stop();
  i = i + 1;
  }
}
public static void main(String[] args) 
{
 Thread1 th1 = new Thread1();
 Thread t1 = new Thread(th1);
 t1.start();
 t1.start(); // Calling the start() method again to alive a dead thread.
 }
}
Output:
       Thread is running
       i: 0
       i: 1
       i: 2
       i: 3
       i: 4
       i: 5
       java.lang.IllegalThreadStateException
	at java.lang.Thread.start(Unknown Source)
	at threadEx.Thread1.main(Thread1.java:23)

In this example program, we are invoking start() method to alive a dead thread. Therefore, we got an exception named IllegalThreadStateException.

In all the preceding programs, when you will have called stop() method on a thread, the compiler generates a warning message like “The method stop from type Thread is deprecated”.

This is because the stop() method is deprecated and should not be used. Deprecated method is that method that is no longer in use. It is annotated by a “deprecated” tag in its method heading.

For example, stop(), suspend(), and resume() method are deprecated methods. Java compiler generates a warning whenever a programmer uses method, class, or field with @Deprecated annotation.

Why is stop method deprecated in Java?


In the early days of Java, Thread class defined a stop() method that simply terminates a thread. But later on Java 1.2 version, stop() method had been deprecated. This is because this method is “inherently unsafe” and can cause serious problem sometimes. Therefore, it should not be used in the program for thread safety.

An interviewer can ask you an interesting question that what logic will you use to stop a thread in the place of stop() method because stop() method had been deprecated from Java 1.2.

Basically, there are two ways through which we can easily stop a thread in java program. They are:
1. By using boolean variable.
2. By using isInterrupted() method

Let’s understand these techniques one by one with an example program.

Stopping a thread by using boolean variable

Program source code 4:

public class Thread1 extends Thread
{
boolean stop = false;
 public void run()
 {
  System.out.println("Thread is running");
  int i = 0;
while(i < 10)
{
 System.out.println("i: " +i);
 if(i == 5)
 if(stop == true) // Come out of run() method.
   return;	   
   i = i + 1;
 }
}
public static void main(String[] args) 
{
 Thread1 th1 = new Thread1();
 Thread t1 = new Thread(th1);
 t1.start();
 th1.stop = true;
 }
}
Output:
      Thread is running
      i: 0
      i: 1
      i: 2
      i: 3
      i: 4
      i: 5

Explanation:

In this example program, first, we created a boolean type variable and initialize it to false. Boolean type variable will store false. Let assume that we want to terminate the thread when i = 5.

So, we will have to store “true” in the boolean type variable. Now, we will check the status of variable in the run() method. If it is true, the thread will execute the return statement and then stop thread.

The syntax to check the status of variable in the run() method is as follows:

public void run()
{
if(stop == true)
   return;
}

Stopping a thread by using isInterrupted() method

To stop a thread using isInterrupted() method, we will modify some code in the previous example program. Look at the following source code.

Program source code 5:

public class Thread1 extends Thread
{	
 public void run()
 {
  System.out.println("Thread is running");
  int i = 0;
while(i < 10)
{
 System.out.println("i: " +i);
if(i == 5)
if(!Thread.currentThread().isInterrupted()) // Come out of run() method.
{
 System.out.println("Status of thread: " +!Thread.currentThread().isInterrupted());
 return;
}
 i = i + 1;  
 }
}
public static void main(String[] args) 
{
 Thread1 th1 = new Thread1();
 Thread t1 = new Thread(th1);
 t1.start();
 }
}
Output:
      Thread is running
      i: 0
      i: 1
      i: 2
      i: 3
      i: 4
      i: 5
      Status of thread: true

Explanation:

In this example program, we used isInterrupt() method for stopping a thread. When isInterrupt() method is called on a running thread, the interrupted status of a thread is set by JVM.

It is a boolean flag that is present on every thread. The status of running thread can be checked by calling isInterrupted() method. It returns true if the current thread is interrupted, otherwise returns false.

To check whether the interrupted status of a thread is set or not, first, call Thread.currentThread() method to get current thread and then call isInterrupted method. The complete syntax is given below:

if(!Thread.currentThread().isInterrupted())
{
 // do more tasks.
  return;
}

The running thread will be terminated when its run() method returns, by executing the return statement, after executing the last statement in the body of method.

Note: interrupted() method is static method that is used to check that the current thread has been interrupted. Calling interrupted() method clears the interrupted status of a thread.

isInterrupted() method is an instance method that is used to that any thread has been interrupted. Calling this method does not change the interrupted status.

Final words

Hope that this tutorial has covered all the important points related to how to stop a thread in Java. I hope that you will have understood this topic and enjoy programming.
Thanks for reading!!!
Next ⇒ Java Thread sleep() method⇐ PrevNext ⇒