Java stop program will be executed when we want to stop a thread in a running or runnable state. When we want a thread to end prematurely, we often utilize the stop() function. Using a volatile boolean variable, you can halt a thread in the current version of Java. Java threads begin operating from the run() function and end when they exit, either naturally or as a result of an error. This characteristic can be used to halt the thread.
The following general syntax is used to invoke the halt method in Java programming:
static void stop()
Because the stop() function is static in nature, the Thread class name may be used to invoke it. When the stop() method is called on a thread, it causes the thread to move to the dead state.
A thread is ended when it transitions from a running or runnable state into a dead state. A thread will end normally if no other thread interrupts it.
A running thread will throw an InterruptedException and terminate if it is interrupted. Even after invoking the start() function, a dead thread cannot be revived. If we try to call the start() method on a dead thread, the start() method will throw an exception named IllegalThreadStateException.
How to stop Running Thread in Java?
Let’s look at an example program where we call the stop() function of the Thread class to end a running thread.
Program code:
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:
When the stop() method is called on a running thread, the next statement is not executed and the thread moved into the dead state and is terminated.
Things to keep in mind:
1. Please make sure the boolean variable used to halt the thread is volatile; if it is not, your thread might not stop and continue to operate indefinitely.
2. When using a while loop, whether, for a game or the main server loop that handles requests, it is usually preferable to check for a boolean variable.
3. It’s good to provide a method to stop the server, which does nothing but change the value of a boolean variable.
4. Using TimeUnit class to pause a thread is better than the Thread.sleep() method because it improves readability.
How to stop Runnable Thread in Java?
For example:
Program code:
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 software, Thread1 enters the runnable state from the neonatal stage when we called the start() method of Thread class on Thread1. The invoking of the stop() function on Thread1 causes it to enter the dead state after it has been moved into the runnable state.
As a result, Thread1 is shut down in a runnable condition. When the stop() function is used following the successful conclusion of the fourth loop, Thread2 is similarly stopped in a running state.
Can a thread again be alive when it goes into the dead state?
A thread cannot be restarted if it is terminated or enters a dead state. An IllegalThreadStateException exception will be thrown if we attempt to call the start() function.
Example program:
Program code:
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)
Through the example above, we’re calling start() to bring a dormant thread back to life. As a result, we received the exception known as IllegalThreadStateException.
When you invoke the stop() method on a thread in any of the programs before, the compiler issues a warning saying something like, “The method stop from type Thread is deprecated.” This is due to the stop() function being obsolete and not being recommended for use. A deprecated method is one that has been abandoned. Its method header has a “deprecated” tag that marks it as such. For example, the stop(), suspend(), and resume() methods are deprecated methods. Java compiler generates a warning whenever a programmer uses a method, class, or field with @Deprecated annotation.
Basically, there are two ways we can easily stop a thread in a Java program:
1. By using a boolean variable.
2. By using isInterrupted() method
Stopping a thread by using a boolean variable
Program code:
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:
First, a boolean variable is created and set to false. False data is stored in boolean variables. Assume that we want to end the stream when i = 5. Therefore, we must put “true” in a boolean variable. We will now verify the variable’s status in the run() function. If this is the case, the thread will run the return statement before being terminated.
The run() method’s syntax for examining a variable’s state 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.
Program code:
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:
For interrupting a thread, we utilized the isInterrupt() function. The interrupted state of a thread is set by JVM when the isInterrupt() function is used on a running thread.
Call the Thread.currentThread() function to retrieve the current thread, then call the isInterrupted method to see if the interrupted state of the thread has been set or not. The entire syntax is shown below:
if(!Thread.currentThread().isInterrupted()) { // do more tasks. return; }
The run() function of the currently active thread will end when it executes the return statement, which comes after the final line in the method’s body.
To sum up
Java’s start() function makes it simple to start a thread, but there is no stop() method, making it quite challenging to end one. Fortunately, the Thread class contains a stop() function. Using a volatile boolean variable, you can halt a thread in the current version of Java. Visit our blog page for additional beneficial Java knowledge.
ONEXT DIGITAL has a team of experts and experienced developers who use cutting-edge technology to provide high-quality Mobile Application Development services. Our digital marketing services can help you reach more customers and grow your business. We are always here and ready to help you.