0

I have a scenario where computer plays TicTacToe game against human player. User enters input on console (System.in) which is read through Scanner obj. After every move, the program makes a decision if any player can make a move which would take the game closer to winning (winner could be human or computer, doesn't matter). Where i'm having issue is, after the program decides that the game has come to a dead end (no matter what move either players make, game can not be won by either), it terminates all threads except one that is waiting for user input on the Scanner object. This is causing my program to hang until user enters something. I want to avoid this. My question is : Can i close/terminate a thread while it is waiting for user input through inputStream ? I tried closing scanner/underlaying System.in stream/interrupting thread programmatically, but none of them took the thread out of the 'waiting for user input' state.

Scanner :

private Scanner scanner = new Scanner(System.in);

Human player thread (which is waiting on user input while either winner is declared or while Referee decides that no player can win) :

    @Override
        public void run() {
            while (!Refree.isWinnerIdentified()) {
                try {
                    System.out.println("Enter next cell location : ");
/*
while execution is waiting on below line for user inputs, all other threads sense that winner is identified and exit. This thread stays in limbo waiting for user inputs
*/
                    String location = scanner.nextLine();

                    //some other code...
                } catch (Exception e) {
                    e.printStackTrace();
                }

            }

        }
DevdattaK
  • 188
  • 9

2 Answers2

-1

Have you tried doing a scanner.close() after the "run" execution terminates?

  • run execution doesn't terminate. That is the main concern. As i mentioned, the thread which seeks user input is polling for something to appear on System.in. In the meantime, game concludes. So, the user input thread is still waiting, while rest of the threads exit from run() method. – DevdattaK Jun 05 '18 at 22:47
  • That won't work since you will still end up with the Scanner waiting for the user input, until the Scanner reads a String the code won't move from the `nextLine()` call – Mattia Righetti Jun 14 '18 at 17:28
-1

You can always call interrupt on the thread waiting for the Scanner input, that should force the thread to resume from a blocking operation.

TwoThe
  • 12,597
  • 3
  • 26
  • 50