0

In my run() method of my Thread class, I am calling a never ending function. I need the thread to run only for a specific duration.

Am not able to control the thread once its started, Is their any way to destroy it?

I have tried yield(), sleep(), etc...

PS - I cannot change the never ending function

Mallikarjuna Reddy
  • 1,212
  • 2
  • 20
  • 33
user2211059
  • 43
  • 1
  • 4

3 Answers3

2

From oracle Java Docs:

public void run(){
    for (int i = 0; i < inputs.length; i++) {
        heavyCrunch(inputs[i]);
        if (Thread.interrupted()) {
             // We've been interrupted: no more crunching.
             return;
        }
    }
}

Your thread should check interrupted condition after each loop to see if it was interrupted. If you are calling a method that just does while(true){} then I am afraid there is no way interrupting it and stop() MUST never be called on a thread.

It is the programmers responsibility to make a long running method responsive to interrupts.

Narendra Pathai
  • 41,187
  • 18
  • 82
  • 120
0

http://docs.oracle.com/javase/1.5.0/docs/guide/misc/threadPrimitiveDeprecation.html answers all your questions.. particularly section What should I use instead of Thread.stop?

Hope it helps

0

This could be too much, but this is how I would solve it, if you do not want to mess with Interrupt.

 public class ThreadTest {
     public static void main(String[] args) throws InterruptedException {
          ThreadTest test = new ThreadTest();
      test.go();
}

void go() throws InterruptedException{
    ExecutorService service = Executors.newSingleThreadExecutor();
    service.execute(new LongRunnable());
    if(!service.awaitTermination(1000, TimeUnit.MILLISECONDS)){
        System.out.println("Not finished within interval");
        service.shutdownNow();
    }
}

}

 class LongRunnable implements Runnable {
      public void run(){
    try{
        //Simultate some work
        Thread.sleep(2000);
    } catch(Exception e){
        e.printStackTrace();
    }
}
 }

Basically you are wrapping your runnable in a ExecutorServie and if it's not finished within the interval, you basically kill it - send the interruption to it.

Eugene
  • 117,005
  • 15
  • 201
  • 306