3

以下片段:

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();
            }
        }
    }

将输出“超时”两次,这是预期的,但之后它将循环抛出 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)

显然我做错了什么,但我不知道是什么。

4

1 回答 1

2

Scanner 类不是线程安全的,正如它的 javadoc 所说:

如果没有外部同步,扫描器对于多线程使用是不安全的。

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

于 2020-03-17T21:03:42.320 回答