gpt4 book ai didi

java - 两个并行线程可以异步执行静态 block 吗

转载 作者:行者123 更新时间:2023-11-30 05:32:43 25 4
gpt4 key购买 nike

我有以下代码。

在任何时间点,i 的打印值是否仍为 0。对于上述执行,我无法重现它。但在生产代码中我得到的值是 0。

我有一个带有静态初始化 block 的生产代码。不知何故,其中一个方法会在静态 block 完成执行之前执行。

class TestStatic {

private int i = 0;

public static TestStatic testStatic = null;

static {
testStatic = new TestStatic();
try {
BufferedReader reader = new BufferedReader(new FileReader("C:\\Users\\I338224\\Documents\\temp\\src\\Test.xml"));
final StringBuilder builder = new StringBuilder();
final DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance();
docBuilderFactory.setIgnoringElementContentWhitespace(true);
docBuilderFactory.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true);
DocumentBuilder docBuilder = null;
docBuilder = docBuilderFactory.newDocumentBuilder();
for(long i=0;i<1000000000;i++);
Document d = docBuilder.parse("C:\\Users\\I338224\\Documents\\temp\\src\\Test.xml");
reader.lines().forEach(line -> builder.append(line).append("\n"));
System.out.println(builder.length());
testStatic.i = 5;
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (SAXException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (ParserConfigurationException e) {
e.printStackTrace();
}
}

public static TestStatic getInstance(){
return testStatic;
}

public void display(){
System.out.println(i);
}
}

public class Test {

public static void main(String[] args) {

Runnable r = () -> {
TestStatic.getInstance().display();
};
Runnable r2 = () -> {
TestStatic.getInstance().display();
};
Thread t1 = new Thread(r);
Thread t2 = new Thread(r2);
t1.start();
t2.start();
}
}

预期的结果是 i 打印的值应该是 5。但实际上是 0。

最佳答案

以下是mcve您的代码。
如果您取消注释 if(true) throw new IllegalStateException("Exception");:

,它 会打印 0
import java.util.concurrent.TimeUnit;

class TestStatic {

private int i = 0;
public static TestStatic testStatic = null;

static {
testStatic = new TestStatic();
try {
TimeUnit.SECONDS.sleep(1);
//if(true) throw new IllegalStateException();
testStatic.i = 5;
} catch (Exception e) {
e.printStackTrace();
}
}

public static TestStatic getInstance(){
return testStatic;
}

public void display(){
System.out.println(i);
}
}

public class Test {

public static void main(String[] args) {
new Thread(() -> TestStatic.getInstance().display()).start();
new Thread(() -> TestStatic.getInstance().display()).start();
}
}

关于java - 两个并行线程可以异步执行静态 block 吗,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57218549/

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