所以我收到了这个错误
java.lang.NullPointerException: Cannot read field "next" because "this.next" is null
at java.base/java.util.LinkedList$ListItr.next(LinkedList.java:897)
at java.base/java.lang.Iterable.forEach(Iterable.java:74)
at org.example.Main.main(Main.java:31)
基本上我有一个在一个地方初始化的单词链接列表
var wordList = new LinkedList<String>()
,然后我创建Executors.newFixedThreadPool(10)
。我创建了 6000 个实现 runners
的 Callable
。他们进行一些处理并向 wordList
添加一个新单词。
那我就做
executorService.invokeAll(runners);
executorService.shutdown();
所以实际上这很有帮助https://stackoverflow.com/a/6916419/7769052。基本上用
LinkedList
替换 CopyOnWriteArrayList
就可以了。我想,因为每个线程都试图同时向单个列表添加一个单词,而且单词数量太多,所以这就是正在发生的事情:
last = elem1; // thread 1
last.next = elem2; // thread 2, thinking that last is the last as if it was thread 1,
// but really it's elem1 so it doesn't have next
当我使用并发列表时,它处理得很好:
var wordList = new CopyOnWriteArrayList<>();