2

In a class, I have a main method and temp method and I'm calling the temp method from main method but after 20 seconds I want to stop these method execution and start again to call temp method.

I have tried to use thread in the code but it won't work.

public static void main(){
  temp();   
 }

 public void temp(){
    // here is my code which takes some time more than 20 second to 
    // so i want to stop these method execution and call again temp method
 }
Anish B.
  • 9,111
  • 3
  • 21
  • 41
thesk
  • 45
  • 9
  • 2
    Any chance you can just simply run your ```temp();``` as a runnable and then terminate it after awaiting 20seconds from your main class? Do this in a while loop – papaya Dec 24 '19 at 05:38
  • Can you just explain because some other code also in main method – thesk Dec 24 '19 at 05:43
  • check this https://stackoverflow.com/questions/2275443/how-to-timeout-a-thread – Sunil Dabburi Dec 24 '19 at 05:59
  • Without knowing what your temp() method is, I have posted a simple thread class, which might look promising for you. – papaya Dec 24 '19 at 06:10
  • in temp method i have generate a number some time it takes more time to match my condition but i do not want to wait more than 20 or 10 sec and call the method again and generate other number – thesk Dec 24 '19 at 07:06

1 Answers1

0

Run your temp method as runnable in a single thread. And interrupt it after 20 seconds. Catch the interrupt exception.

class TempThread implements Runnable { 

// to stop the thread 
private boolean exit; 

private String name; 
Thread t; 

TempThread(String threadname) 
{ 
    name = threadname; 
    t = new Thread(this, name); 
    exit = false; 
    t.start();
} 


public void run() 
{ 
    while (!exit) { 
        try { 
            Thread.sleep(100); 
        } 
        catch (InterruptedException e) { 
            System.out.println("Caught:" + e); 
        } 
    } 
} 


public void stop() 
{ 
    exit = true; 
} 
} 

In your main class now wait for 20 seconds and call the stop() method. Unsure what your temp method here is.

static void main(String[] args){

  TempThread t1 = new TempThread("runniing a temp"); 

  try{
    Thread.sleep(20000); //wait 20 seconds
  }catch (Exception e){
    e.printStackTrace();
  }
  t1.stop();
}
papaya
  • 1,505
  • 1
  • 13
  • 26
  • but where should i put my temp method code – thesk Dec 24 '19 at 06:56
  • inside the ```run``` method. This is just one sample on how to do it. There are many other ways including using ```Future.get(timeout in seconds)``` – papaya Dec 24 '19 at 07:02