0

i'm very new to java coding. i have a thread.sleep () to pause the execution and would like to write a code to resume execution with a key press on console. here is my code:

int pausetime = 9000; //user input
if (pausetime!=0){
thread.sleep(pausetime)}

for example user enters 9000 and decides to resume the execution at 5 secs, code should resume the execution with any key press on the console.

NTP
  • 1

1 Answers1

0

If you are using Thread.sleep then you have to interrupt this thread which throws exception that you have to handle and it continues execution.

Here is a sample code in which I am pausing the thread in run method while waiting for the input in main method and then interrupting above thread after user input

void run(){
 try {
            Thread.sleep(15000);
                System.out.println("sleeping");
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

System.out.println("Runnig thread again");
}
...
main(...){
  Thread t= new Thread(task,"start");
    t.start();
    a=new InputStreamReader(System.in);
    char[] ac=new char[5];
    try {
        a.read(ac);
    } catch (IOException e){    
        e.printStackTrace();
    }
    if(ac.length>0) 
        t.interrupt();
}
rakesh
  • 4,368
  • 1
  • 19
  • 13