Wednesday, May 12, 2010

Stopping a timed out thread



Some threads may run for long time than expected, to control this threads we may want to stop the thread if they are running for long time than expected. the following is an small example for how to do this.

The class MyThread is a thread which will be created from the ThreadTest class. MyThread has a private property requestedToStop which will be used to stop the thread (as stop method of the Thread is deprecated, this is one of the suggested approach to stop the thread). 


Class MyThread





package com.blogger.technoant;

public class MyThread extends Thread{
     
      private boolean requestedToStop=false;   
     
      @Override
      public void run() {
            while(!this.requestedToStop){
                  System.out.println("I am running....");
            }          
      }
     
      public void requestStop(){
            this.requestedToStop=true;
      }

}



Class - ThreadTest



package com.blogger.technoant;

public class ThreadTest  {
     
      public static void main(String args[]) throws Exception{
           
            final long TIMOUT_TIME=5*1000;
           
            MyThread myThread=new MyThread();
           
            Thread t1=new Thread(myThread);    
           
            t1.start();      
            t1.join(TIMOUT_TIME);        
           
            if(t1.isAlive()){
                  myThread.requestStop();
                  throw new Exception("Timed out. Thread executing for more than "+TIMOUT_TIME+" millisecs");
            }    
           
           
      }

}

I hope this example will help on how to stop thread on timeout.

One question may arise as the MyThread has extended Thread instead of implementing Runnable (which is always preferred). In MyThread class actually I am trying to extend the functionality of the Thread by adding smooth stop, so I feel extending thread has reason here.




Classification: How to Stop Thread, How to restrict thread execution, restrict thread execution time, control thread execution, stopping thread

No comments:

Post a Comment