Coding this is easy, but coding what you THINK they want is VERY difficult.
(1) How can your code run longer than 4 seconds if you had to put a sleep of 3 and a half seconds in the main program part ?
(2) If you interrupt it, from the main program, it has already completed, because it only sleeps a second, and the hard coded numSeconds that you pass and have to iterate through takes 3 seconds. So you're never interrupting it.
package com.codegym.task.task16.task1617;
/*
Countdown at the races
*/
public class Solution {
public static volatile int numSeconds = 3;
public static void main(String[] args) throws InterruptedException {
RacingClock clock = new RacingClock();
Thread.sleep(3500);
clock.interrupt();
}
public static class RacingClock extends Thread {
public RacingClock() {
start();
}
public void run() {
try{
Thread thisThread = Thread.currentThread();
while (!interrupted()){
Thread.sleep(1000);
if (numSeconds > 0){
System.out.print(numSeconds + " ");
}
else{
System.out.print("Go!");
thisThread.interrupt();
}
numSeconds--;
}
}
catch (InterruptedException e){
System.out.print("Interrupted!");
}
}
}
}
break
in the else block to immediately terminate the while loop after printing "Go!", negating the need for an extra Thread object.