Can anybody refer me to a better explanation?
I tried many things but do not understand the logic behind multi threads. I reread the example several times but can't find out how it actually works in details.
My first question is:
1) Why does it seem that I created an infinite loop while I do get output?
2) My output for this code is now => //output 3 2 3 1 Go!Go! Why does it jump back from 2 to 3 and then to 1 skipping 2?
3) Why does it not jump out of the loop? it prints Go! twice even though I put a return after the print command "Go!".
4) Do we need to create a second Thread for the run() method? If so why or why not? Very confused about this.
5) I understand that the interrupt() method will automatically return an interrupted message. So why does it ask for this again after I state the Thread.sleep(1000) in the run() method?
In short I do not understand this concept at all so where can I find a proper explanation? Your help is very much appreciated.
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();
//write your code here
Thread clockThread = new Thread(clock);
clockThread.start();
Thread.sleep(3500);
clockThread.interrupt();
}
public static class RacingClock extends Thread {
public RacingClock() {
start();
}
public void run() {
//write your code here
try{
Thread current = Thread.currentThread();//a second tread for the run()
Thread.sleep(1000);//sleeps after 1 second
while (numSeconds > 0)
{
//Thread.sleep(1000);
System.out.print(numSeconds + " ");
numSeconds--;
}
System.out.print("Go!");//output 3 2 3 1 Go!Go!
return;
}
catch (InterruptedException e){}
}
}
}