package com.codegym.task.task16;
public class Solution {
public static volatile int numSeconds = 4;
public static void main(String[] args) throws InterruptedException {
RacingClock clock = new RacingClock();
//write your code here
Thread.sleep(3500);
clock.interrupt();
}
public static class RacingClock extends Thread {
public RacingClock() {
start();
}
public void run() {
//write your code here
try {
int constant = numSeconds;
while(numSeconds > 0) {
System.out.print(numSeconds + " ");
Thread.sleep(1000);
numSeconds--;
}
if(constant<=3) {
System.out.println("Go!");
}
} catch (Exception e) {System.out.print("Interrupted!"); }
}
}
}
numSeconds = 4; Why when numSeconds is more than 3 it is goes to catch?
Resolved
Comments (4)
- Popular
- New
- Old
You must be signed in to leave a comment
AnnemiekFF
3 June 2020, 10:45solution
Because you have an interrupt in the main which runs after 3500 miliseconds (aka 3,5 seconds) so it will be interrupted before it can get to 4.
+2
Prassha
3 June 2020, 12:15
Thank you for the explanation. it clear a lot for me.
So every time we call the interrupt method it will throw exception. is that is correct?
Therefore if I want to write a code saying 5 seconds after eating drink water
eat action
5 second delay
call interrupt
in the catch (print (drink water))
Just trying to understand in layman's terms. :-)
Genuine thank you from my heart.
+1
AnnemiekFF
3 June 2020, 14:29useful
This code here will interrupt your clock after 3,5 sec. If you want it to count to 5, Thread.sleep should be at least 5001ms.
+1
Prassha
3 June 2020, 15:46
Thank you.
+1