I searched StackOverflow but I couldnt find the answer to my question.
I have a class Main:-
public class Main {
public static Thread game = new Thread(new Start());
public static void main(String[] args) {
game.start();
try {
game.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
And I have the game Thread(start class):-
public class Start implements Runnable {
private Timer timer = new Timer();
private Thread timerThread = new Thread(timer, "timer");
@Override
public void run() {
...
try {
play();
}
catch(IOException e) {
e.printStackTrace();
}
}
public void play() throws IOException {
...
timerThread.run();
System.out.print("Enter a letter: ");
char input = sc.next().toUpperCase().charAt(0);
...
if(isPlaying) play();
}
}
And I have the Timer class:-
public class Timer implements Runnable {
@Override
public void run() {
for (int i = 1; i <= 15; i++) {
try {
System.out.println(i);
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
Main.game.interrupt();
}
}
Now the problem comes that when I start the game, the timer also starts. But at the end of 15 seconds, Timer thread stops. But the program didn't stop executing.
After 15 seconds, the compiler is still willing to take the input. After the input, the program ceases.
I want to immediately force stop the thread. Soon after 15 seconds, I want to stop the execution of the game thread at that very instant.
I looked over at some Multithreading tutorials on Youtube and some previously asked questions at StackOverflow but I failed to find a solution.