如何java不阻止,如何阻止Java Scanner接受输入

So, I am working on a quiz taking program that works from the command line and the quizzes have time limits. What I want to do, is to stop the quiz right when the user's time is up even if they're in the middle of answering a question. I am using Java's Scanner to get the user's input, so I want to essentially tell the Scanner object to terminate even if it's in the middle of accepting input.

Now, I know that I can retroactively punish a user for going over time after the fact, but I simply want the quiz to terminate once the time limit has been exceeded. Is there any way to do this with multithreading for example?

解决方案

A Java Scanner is using blocking operations. It is not possible to stop it. Not even using Thread.interrupt();

You can however read using a BufferedLineReader and be able to stop the thread. It's not a neat solution, as it involves pausing for short moments (otherwise it would use 100 % CPU), but it does work.

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();

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值