Question

So I'm trying to make a console app that imposes a time limit to user. User is expected to enter a certain number, but after a certain amount of milis (10 secs), it will break out of that input mode and tell user that time has expired and program moves on. This is my code:

    final InputStreamReader isr = new InputStreamReader(System.in);
    final BufferedReader br = new BufferedReader(isr);

    TimerTask task = new TimerTask() {
        @Override
        public void run() {
            try {
                System.in.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    };

    new Timer().schedule(task, 10000);

    try {
        String line = br.readLine();
        if (line == null) {
            System.out.println("TIME EXPIRED");
        } else {
            System.out.println("TEXT: " + line);
        }
    } catch (IOException e) {
        e.printStackTrace();
    }

    System.out.println("END");

It seems to work properly, except that the program seems to be stuck at the input mode indefinitely. It spits out "END" to the console, but the program doesn't terminate. It seems it's still expecting input from user. What did I do wrong? Or is there a better way to do this?

Was it helpful?

Solution

Timer is not a daemon thread, it won't terminate itself unless you call timer.cancel() or create the timer in this way:

new Timer(true).schedule(task, 10000);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top