how to interrupt a scanner.nextline() call

前端 未结 4 439
忘了有多久
忘了有多久 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:47

    Another version of geri's answer would be:

    ExecutorService executor = Executors.newFixedThreadPool(1);
    
    Future future = executor.submit(() -> {
        try (Scanner in = new Scanner(System.in)) {
            return in.nextLine();
        }
    });
    
    try {
        return future.get(5, TimeUnit.SECONDS);
    } catch (InterruptedException | ExecutionException | TimeoutException e1) {
        return ...;
    }
    

提交回复
热议问题