How To Terminate Thread Inwards Coffee Code Example

The thread is 1 of of import Class inwards Java in addition to multithreading is close widely used a feature,but in that place is no clear agency to halt Thread inwards Java. Earlier in that place was a halt method exists inwards Thread Class precisely Java deprecated that method citing roughly security reason. By default, a Thread stops when execution of run() method complete either unremarkably or due to whatever Exception.In this article, nosotros volition How to Stop Thread inwards Java past times using a boolean State variable or flag. Using a flag to halt Thread is a really pop way  of stopping the thread in addition to it's every bit good rubber because it doesn't produce anything exceptional rather than helping run() method to complete itself.


How to Stop Thread inwards Java

As I said before Thread inwards Java volition halt in 1 trial run() method finished. Another of import indicate is that yous tin non restart a Thread which run() method has finished already , yous volition larn an IllegalStateExceptio, hither is a Sample Code for Stopping Thread inwards Java.


Sample Code to Stop Thread inwards Java



    somebody shape Runner extends Thread{
    boolean bExit = false;
  
    populace void exit(boolean bExit){
        this.bExit = bExit;
    }
  
    @Override
    populace void run(){
        while(!bExit){
            System.out.println("Thread is running");
                endeavour {
                    Thread.sleep(500);
                } select grip of (InterruptedException ex) {
                    Logger.getLogger(ThreadTester.class.getName()).log(Level.SEVERE, null, ex);
                }
        }
    }
}
    
    

Should nosotros brand bExit Volatile
The thread is 1 of of import Class inwards Java in addition to multithreading is close widely used a feat How to Stop Thread  inwards Java  Code  ExampleSince every Thread has its ain local retentivity inwards Java its skillful exercise to brand bExit volatile because nosotros may modify the value of bExit from whatever thread in addition to come inwards volatile guarantees that Runner volition every bit good come across whatever update done before making bExit.

That’s all on how to halt the thread inwards Java , permit me know if yous discovery whatever other agency of stopping threads inwards Java without using deprecated stop() method.


Further Learning
Multithreading in addition to Parallel Computing inwards Java
Java Concurrency inwards Practice - The Book
How to discovery in addition to Avoid Deadlock inwards Java

Sumber https://javarevisited.blogspot.com/

0 Response to "How To Terminate Thread Inwards Coffee Code Example"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel