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.