public class C{
static {
a();
}
private static int sum;
public static int getSum() {
a();
return sum;
}
private static boolean b = false;
private static synchronized void a() {
if (!b) {
for (int i = 0; i < 100; i++)
sum += i;
b = true;
}
}
}
public class D {
public static void main(String[] args) {
System.out.println(C.getSum());
}
}
//打印C类的getSum的返回值,会先加载C类,执行静态代码块中的代码,此时b为false,所以sum被增加到了4950
//并且加b置为了true,然后在执行getSum的时候,由于b为ttrue,就不会再给sum增加值,但是打印的结果是9900
//而不是4950,求解!!! |