Saturday 9 August 2014

Kill thread in Java

You can kill a thread using Thread stop method.

But stop() is deprecated
When a thread is stopped, then the resources locked by this thread got released. So if a thread stopped abnormally then the objects monitored by this thread are in inconsistent state. Which leads to abnormal behavior to your application.

how to stop a thread
You can stop a thread by using simple flag or interrupting the thread.

Using flag
Simple solution is use a flag to check whether to proceed the thread execution or not.

public class ThreadSample implements Runnable{
    
    volatile boolean flag = true;
    
    @Override
    public void run(){
        while(flag){
            /* Do Some Processing here */
        }
        System.out.println("Thread finishing Execution");
    }
    
    void stopThread(){
        flag = false;
    }
    
    public static void main(String args[]){
        ThreadSample t1 = new ThreadSample();
        Thread thrd = new Thread(t1);
        
        thrd.start();
        t1.stopThread();
    }
    
}

Output
Thread finishing Execution

Using interrupt
public class ThreadSample implements Runnable{
    
    volatile boolean flag = true;
    
    @Override
    public void run(){
        while(!Thread.currentThread().isInterrupted()){
            /* Do Some Processing here */
        }
        System.out.println("Thread finishing Execution");
    }
    
    void stopThread(){
        flag = false;
    }
    
    public static void main(String args[]) throws InterruptedException{
        ThreadSample t1 = new ThreadSample();
        Thread thrd = new Thread(t1);
        
        thrd.start();
        Thread.sleep(2000);
        thrd.interrupt();
    }
}

Output
Thread finishing Execution


 

                                                             Home

No comments:

Post a Comment