How to cease a thread inwards Java? Example

Today we're going to larn close how to halt a thread inwards Java. It's slowly to start a thread inwards Java because you lot accept a start() method simply it's hard to halt the thread because at that spot is no working stop() method. Well, at that spot was a stop() method inwards Thread class, when Java was starting fourth dimension released simply that was deprecated later. In today's Java version, You tin halt a thread past times using a boolean volatile variable.  If you lot remember, threads inwards Java start execution from run() method as well as stop, when it comes out of run() method, either unremarkably or due to whatever exception. You tin leverage this belongings to halt the thread. All you lot demand to practice is  create a boolean variable e.g. bExit or bStop. Your thread should cheque its value every iteration as well as comes out of the loop as well as after from run() method if bExit is true. 

In guild to halt the thread, you lot demand to set the value of this boolean variable to truthful when you lot desire to halt a running thread. Since you lot are setting this variable from a dissimilar thread e.g. primary thread, it's of import to grade this variable volatile, otherwise, it's possible for the running thread to cache its value as well as never cheque dorsum to primary retentivity for updated value as well as running infinitely.

When you lot brand a variable volatile, running thread volition non cache its value inwards its local stack as well as ever refer primary memory. The volatile variable besides provides happens earlier guarantee, which tin travel used to synchronize values. If you lot desire to empathise multi-threading as well as concurrency inwards the correct way, I strongly propose reading Java Concurrency inwards Practice twice. It's i of the most accurate, thorough as well as practical books inwards Java multi-threading.




Stopping a Thread inwards Java - An Example

Here is our sample code instance to halt a thread inwards Java. You tin run into that inwards this example, the primary thread is starting fourth dimension starting a thread as well as later it's stopping that thread past times calling our stop() method, which uses a boolean volatile variable to halt running thread e.g. Server.  From the output, it's clear that our Server, which implements Runnable is running fine until main() method called the stop() method, the solely as well as then value of boolean volatile variable exit is gear upward to true. In adjacent iteration, our Server thread checks as well as detect this value true, so it come upward out of the loop as well as run() method, which agency your thread is forthwith stopped.

s slowly to start a thread inwards Java because you lot accept a  How to halt a thread inwards Java? Example


Here is the Java programme to demonstrate how to halt a thread inwards Java using boolean volatile variable, You tin besides run into here for similar approach.

import static java.lang.Thread.currentThread;  import java.util.concurrent.TimeUnit;  /**  * Java Program to demonstrate how to halt a thread inwards Java.  * There is a stop() method inwards Thread degree simply its deprecated   * because of deadlock as well as other issue, simply its slowly to write  * your ain stop() method to halt a thread inwards Java.   *   * @author java67  */  public class ThreadStopDemo {      public static void main(String args[]) throws InterruptedException {         Server myServer = new Server();          Thread t1 = new Thread(myServer, "T1");         t1.start();                  //Now, let's halt our Server thread         System.out.println(currentThread().getName() + " is stopping Server thread");         myServer.stop();                  //Let's await to run into server thread stopped          TimeUnit.MILLISECONDS.sleep(200);                  System.out.println(currentThread().getName() + " is finished now");     } }  class Server implements Runnable{     private volatile boolean acquire out = false;          public void run() {         while(!exit){             System.out.println("Server is running.....");         }                  System.out.println("Server is stopped....");     }          public void stop(){         acquire out = true;     } }  Output Server is running..... Server is running..... Server is running..... Server is running..... Server is running..... Server is running..... Server is running..... Server is running..... Server is running..... Server is running..... primary is stopping Server thread Server is running..... Server is stopped.... primary is finished now


Things to remember

1) Please ensure that boolean variable which is used to halt the thread is volatile, otherwise, inwards the worst instance your thread may non halt as well as run infinitely, Why? because, inwards the absence of whatever synchronization pedagogy e.g. volatile modifier here, the compiler is costless to cache the value of boolean variable exit, which agency fifty-fifty if the primary thread makes it true, Server volition ever run into it false, therefore running infinitely. This concept is ofttimes tested inwards Java interviews every bit well.

2) It's ever ameliorate to cheque for a boolean variable inwards your spell loop, it could travel your game loop or primary server loop used to procedure request.

3) It's expert to render a method to halt the server, which does zilch simply alter the value of boolean variable.

4) Using TimeUnit degree to time out a thread is ameliorate than Thread.sleep() method because it improves readability. You know upward front end that whether thread is stopping for 2 millisecond or 2 second, which was non visible inwards instance of Thread.sleep().  See here to larn to a greater extent than close TimeUnit class.


That's all close how to halt a thread inwards Java. Make certain to cheque for stopping status inwards a spell loop as well as ensure that the boolean volatile variable. This volition guarantee 2 things, starting fourth dimension the thread which is checking this boolean variable volition non cache its value inwards its local cache as well as minute whatever alter made on i thread earlier setting this volatile boolean variable volition travel visible to other thread every bit well. In the existent world, though, you lot may demand to laissez passer on your thread around fourth dimension to complete pending task, unloose resources as well as practice cleanup earlier stopping.

Further Learning
Java Fundamentals Part 1,2
Java Concurrency inwards Practice
Applying Concurrency as well as Multi-threading to Common Java Patterns

If you lot similar this curt tutorial as well as interested to larn Java inwards deep, hither are twosome of to a greater extent than interesting articles you lot volition relish :
  • What is divergence betwixt transient as well as volatile variable inwards Java? [answer]
  • How to time out a thread inwards Java? [example]
  • What is divergence betwixt a thread as well as a process? [answer]
  • What is divergence betwixt implements Runnable as well as extends Thread inwards Java? [answer]
  • 10 things you lot should know close Thread inwards Java? [article]
  • When to role wait() as well as sleep() method inwards Java? [answer]
  • Difference betwixt Callable as well as Runnable interface inwards Java? [answer]


Subscribe to receive free email updates:

0 Response to "How to cease a thread inwards Java? Example"

Posting Komentar