因此,我正在开发一个可从命令行运行的测验程序,测验有时间限制。我想做的是,即使用户正在回答问题,也要在他们的时间用完后立即停止测验。我正在使用Java的Scanner来获取用户的输入,因此我想本质上告诉Scanner对象终止,即使该对象处于接受输入的过程中。

现在,我知道我可以追溯事实之后对用户的惩罚,但是我只是希望一旦超过时间限制就终止测验。例如,有什么方法可以执行此操作吗?

最佳答案

Java扫描程序正在使用阻止操作。无法停止它。甚至不使用Thread.interrupt();

但是,您可以使用BufferedLineReader进行读取,并且可以停止线程。这不是一个很好的解决方案,因为它涉及暂停片刻(否则将使用100%CPU),但它确实可以工作。

public static class ConsoleInputReadTask {
    private final AtomicBoolean stop = new AtomicBoolean();

    public void stop() {
        stop.set(true);
    }

    public String requestInput() throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        System.out.println("ConsoleInputReadTask run() called.");
        String input;
        do {
            System.out.println("Please type something: ");
            try {
                // wait until we have data to complete a readLine()
                while (!br.ready() && !stop.get()) {
                    Thread.sleep(200);
                }
                input = br.readLine();
            } catch (InterruptedException e) {
                System.out.println("ConsoleInputReadTask() cancelled");
                return null;
            }
        } while ("".equals(input));
        System.out.println("Thank You for providing input!");
        return input;
    }
}

public static void main(String[] args) {
    final Thread scannerThread = new Thread(new Runnable() {
        @Override
        public void run() {
            try {
                String string = new ConsoleInputReadTask().requestInput();
                System.out.println("Input: " + string);
            }
            catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
    });
    scannerThread.start();

    new Thread(new Runnable() {
        @Override
        public void run() {
            try {
                Thread.sleep(5000);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
            scannerThread.interrupt();
        }
    }).start();
 }

09-25 17:20
查看更多