未来的任务抛出由 IndexOutOfBoundsException 引起的 ExecutionException,而据我所知,我没有使用数组

Future task throws ExecutionException caused by IndexOutOfBoundsExceptionwhile I, to the best of my knowledge am using no array

以下代码段:

public void handleInput() {
        Scanner sc = new Scanner(System.in);
        int x = 3;

        while (true) {

            FutureTask<String> readNextLine = new FutureTask<String>(sc::nextLine);

            ExecutorService executor = Executors.newFixedThreadPool(10);
            executor.execute(readNextLine);

            try {
                String line = readNextLine.get(x * 1000, TimeUnit.MILLISECONDS);

            } catch (TimeoutException e) {
                System.out.println("timed out");
            } catch (ExecutionException | InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

将输出 "timed out" 两次,这是预期的,但之后它将循环抛出 ExecutionException,堆栈如下

java.util.concurrent.ExecutionException: java.lang.IndexOutOfBoundsException: end
    at java.base/java.util.concurrent.FutureTask.report(FutureTask.java:122)
    at java.base/java.util.concurrent.FutureTask.get(FutureTask.java:205)
    at traceCalls.Trace.handleInput(Trace.java:32)
    at main.main(main.java:11)
Caused by: java.lang.IndexOutOfBoundsException: end
    at java.base/java.util.regex.Matcher.region(Matcher.java:1515)
    at java.base/java.util.Scanner.findPatternInBuffer(Scanner.java:1089)
    at java.base/java.util.Scanner.findWithinHorizon(Scanner.java:1791)
    at java.base/java.util.Scanner.nextLine(Scanner.java:1649)
    at java.base/java.util.concurrent.FutureTask.run$$$capture(FutureTask.java:264)
    at java.base/java.util.concurrent.FutureTask.run(FutureTask.java)
    at java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1128)
    at java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:628)
    at java.base/java.lang.Thread.run(Thread.java:834)

显然我做错了一些事情,但我不知道是什么。

扫描器 class 不是线程安全的,正如它的 javadoc 所说:

A Scanner is not safe for multithreaded use without external synchronization.

因此,如果您真的想在多个线程中读取 System.in(很可能您不需要!),您需要为每个线程创建扫描器,或使用同步。