how to interrupt a scanner.nextline() call

前端 未结 4 525
忘了有多久
忘了有多久 2021-01-22 19:58

There are many threads on SO about interrupting reading the system.in but what I am looking for here is some kind of advice as to how to best code what I am trying to achieve.

4条回答
  •  青春惊慌失措
    2021-01-22 20:39

    A FutureTask together with a lambda expression can also be used:

    FutureTask readNextLine = new FutureTask(() -> {
      return scanner.nextLine();
    });
    
    ExecutorService executor = Executors.newFixedThreadPool(2);
    executor.execute(readNextLine);
    
    try {
      String token = readNextLine.get(5000, TimeUnit.MILLISECONDS);
      ...
    } catch (TimeoutException e) {
      // handle time out
    }
    

提交回复
热议问题