gpt4 book ai didi

java - 为什么这个片段抛出 NullPointerException

转载 作者:行者123 更新时间:2023-11-29 05:14:41 24 4
gpt4 key购买 nike

这是我的代码截图

public void testThread() throws Exception {
final List<String> list = new ArrayList<String>();
ExecutorService checkPool = Executors.newFixedThreadPool(100);
for (int i = 1; i <= 100000; i++) {
checkPool.execute(new Runnable() {
public void run() {
list.add("abc");
}
});
}
checkPool.shutdown();
try {
checkPool.awaitTermination(Integer.MAX_VALUE, TimeUnit.SECONDS);
} catch (InterruptedException e) {
e.printStackTrace();
}
for (int i = 0; i < list.size(); i++) {
System.out.println(list.get(i).toString());
}
}

我在 junit 测试中运行它,但它抛出 NullPointerException

System.out.println(list.get(i).toString());    

我不知道为什么会这样!

最佳答案

当你在你的 list 上执行 add() 时你有竞争条件。

当您运行 execute() 时,无法保证 Runnable 对象的 run() 方法将实际运行。

为防止这种情况,您需要使用 synchronized 关键字来锁定对 list 的访问:

public void run() {
synchronized (list) {
list.add("abc");
}
}

关于java - 为什么这个片段抛出 NullPointerException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27007511/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com