set timeout for user's input

前端 未结 3 2025
半阙折子戏
半阙折子戏 2020-11-29 13:32

Is it possible to set timer for user\'s input? Wait 10 seconds - do next operation and etc. I mean for example

 //wait several seconds{
 String s = new Buff         


        
相关标签:
3条回答
  • 2020-11-29 13:44

    Not right out of the box, no. Normally the Reader only breaks out of a read() call when another thread closes the underlying stream, or you reach the end of the input.

    Since read() is not all that interruptible this becomes a bit of a concurrent programming problem. The thread that knows about the timeout will need to be able to interrupt the thread that's trying to read the input.

    Essentially, the reading thread will have to poll the Reader's ready() method, rather than getting locked in read() when there's nothing to read. If you wrap this polling and waiting operation in a java.util.concurrent.Future, then you call the Future's get() method with a timeout.

    This article goes into some detail: http://www.javaspecialists.eu/archive/Issue153.html

    0 讨论(0)
  • 2020-11-29 13:44
     BufferedReader inputInt = new BufferedReader(new InputStreamReader(System.in));
     Robot enterKey = new Robot();
     TimerTask task = new TimerTask() {
       public void run() {
                          enterKey.keyPress(KeyEvent.VK_ENTER);
                         }
     };
    
     Timer timer = new Timer();
     timer.schedule(task, 30 * 1000);
     userInputanswer = inputInt.read();
     timer.cancel();
    
    0 讨论(0)
  • 2020-11-29 13:47

    A slightly easier way to do this than Benjamin Cox's answer would be to do something like

    int x = 2; // wait 2 seconds at most
    
    BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
    long startTime = System.currentTimeMillis();
    while ((System.currentTimeMillis() - startTime) < x * 1000
            && !in.ready()) {
    }
    
    if (in.ready()) {
        System.out.println("You entered: " + in.readLine());
    } else {
        System.out.println("You did not enter data");
    }
    

    This will, however consume more resources than his solution.

    0 讨论(0)
提交回复
热议问题