1

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?

4

1 回答 1

1

Timer 不是守护线程,除非您调用 timer.cancel() 或以这种方式创建计时器,否则它不会自行终止:

new Timer(true).schedule(task, 10000);
于 2012-04-02T21:23:51.270 回答