Tuesday, December 10, 2019

How To Goal A Thread Inwards Java? Example

Today we're going to larn most how to halt a thread inwards Java. It's slow to start a thread inwards Java because you lot convey a start() method but 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 but that was deprecated later. In today's Java version, You tin terminate 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 commonly or due to whatsoever exception. You tin terminate leverage this holding to halt the thread. All you lot demand to exercise is  create a boolean variable e.g. bExit or bStop. Your thread should depository fiscal establishment friction match its value every iteration as well as comes out of the loop as well as afterward from run() method if bExit is true. 

In club 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 unlike thread e.g. nous thread, it's of import to score this variable volatile, otherwise, it's possible for the running thread to cache its value as well as never depository fiscal establishment friction match dorsum to nous retentiveness 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 e'er refer nous memory. The volatile variable too provides happens earlier guarantee, which tin terminate survive used to synchronize values. If you lot desire to sympathize multi-threading as well as concurrency inwards the correct way, I strongly advise reading Java Concurrency inwards Practice twice. It's ane 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 illustration to halt a thread inwards Java. You tin terminate come across that inwards this example, the nous 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 exclusively as well as so value of boolean volatile variable exit is fix to true. In adjacent iteration, our Server thread checks as well as respect this value true, so it come upwardly out of the loop as well as run() method, which way your thread is straight off stopped.

here for like 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 cast but its deprecated   * because of deadlock as well as other issue, but its slow 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 facial expression to come across 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..... nous is stopping Server thread Server is running..... Server is stopped.... nous 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 illustration your thread may non halt as well as run infinitely, Why? because, inwards the absence of whatsoever synchronization pedagogy e.g. volatile modifier here, the compiler is gratuitous to cache the value of boolean variable exit, which way fifty-fifty if the nous thread makes it true, Server volition e'er come across it false, hence running infinitely. This concept is oftentimes tested inwards Java interviews every bit well.

2) It's e'er amend to depository fiscal establishment friction match for a boolean variable inwards your spell loop, it could survive your game loop or nous server loop used to procedure request.

3) It's adept to supply a method to halt the server, which does nil but alter the value of boolean variable.

4) Using TimeUnit cast to intermission a thread is amend than Thread.sleep() method because it improves readability. You know upwardly front end that whether thread is stopping for 2 millisecond or 2 second, which was non visible inwards illustration of Thread.sleep().  See here to larn to a greater extent than most TimeUnit class.


That's all most how to halt a thread inwards Java. Make certain to depository fiscal establishment friction match for stopping status inwards a spell loop as well as ensure that the boolean volatile variable. This volition guarantee ii things, starting fourth dimension the thread which is checking this boolean variable volition non cache its value inwards its local cache as well as instant whatsoever alter made on ane thread earlier setting this volatile boolean variable volition survive visible to other thread every bit well. In the existent world, though, you lot may demand to scope your thread only about fourth dimension to complete pending task, unloosen resources as well as exercise cleanup earlier stopping.

Further Learning
Multithreading as well as Parallel Computing inwards Java
answer]
  • How to intermission a thread inwards Java? [example]
  • What is departure betwixt a thread as well as a process? [answer]
  • What is departure betwixt implements Runnable as well as extends Thread inwards Java? [answer]
  • 10 things you lot should know most Thread inwards Java? [article]
  • When to operate wait() as well as sleep() method inwards Java? [answer]
  • Difference betwixt Callable as well as Runnable interface inwards Java? [answer]


  • No comments:

    Post a Comment