gpt4 book ai didi

java - 为什么调用空 Atomic 类的方法不会产生异常?

转载 作者:行者123 更新时间:2023-12-02 14:55:55 25 4
gpt4 key购买 nike

import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicInteger;

public class _7_Synchronizing_Data_Access {
private AtomicInteger count;

private void incrementAndReport() {
System.out.print(count.incrementAndGet() + "here"); //does not print
}

public static void main(String[] args) {
ExecutorService service = null;
try {
service = Executors.newFixedThreadPool(20);
_7_Synchronizing_Data_Access manager = new _7_Synchronizing_Data_Access();
for (int i = 0; i < 10; i++)
service.submit(() -> manager.incrementAndReport());
} finally {
if (service != null)
service.shutdown();
}
}
}

运行这个程序什么都不输出。甚至没有 NullPointerException。如您所见,我没有实例化 count。我希望它会引发错误。这是为什么?

最佳答案

NullPointerException异常被抛出并被捕获,但为了看到它们,你需要检查 Future service.submit 返回的实例调用:

按如下方式更改循环:

for (int i = 0; i < 10; i++) {
Future f = service.submit(() -> manager.incrementAndReport());
try {
System.out.println (f.get ());
}
catch (ExecutionException exex) {
System.out.println (exex);
}
catch (InterruptedException intEx) {
System.out.println (intEx);
}
}

将输出:

java.util.concurrent.ExecutionException: java.lang.NullPointerException
java.util.concurrent.ExecutionException: java.lang.NullPointerException
java.util.concurrent.ExecutionException: java.lang.NullPointerException
java.util.concurrent.ExecutionException: java.lang.NullPointerException
java.util.concurrent.ExecutionException: java.lang.NullPointerException
java.util.concurrent.ExecutionException: java.lang.NullPointerException
java.util.concurrent.ExecutionException: java.lang.NullPointerException
java.util.concurrent.ExecutionException: java.lang.NullPointerException
java.util.concurrent.ExecutionException: java.lang.NullPointerException
java.util.concurrent.ExecutionException: java.lang.NullPointerException

如果将 System.out.println(count.incrementAndGet() + "here"); 括起来,您还会看到会抛出异常。带有 try-catch 的语句:

private void incrementAndReport() {
try {
System.out.println(count.incrementAndGet() + "here"); //does not print
}
catch (Exception exc) {
System.out.println (exc);
}
}

关于java - 为什么调用空 Atomic 类的方法不会产生异常?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52923151/

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