【发布时间】:2013-07-19 01:15:22
【问题描述】:
我正在阅读“Java Concurrency in Practice”并尝试编写一段代码,以表明第 3.5.1 章中作为示例介绍的类确实会引入问题。
public class Holder {
public int n;
public Holder(int n) {
this.n = n;
}
public void assertSanity() {
if (n != n) {
throw new AssertionError("sanity check failed!!");
}
}
}
那里说如果按照下面的方式使用(我相信是因为该字段是公共的,可能会出现并发问题。
public Holder holder;
public void initialize() {
holder = new Holder(42);
}
所以我想出了这段代码,看看有没有什么不好的事情发生。
public class SanityCheck {
public Holder holder;
public static void main(String[] args) {
SanityCheck sanityCheck = new SanityCheck();
sanityCheck.runTest();
}
public void runTest() {
for (int i = 0; i < 100; i++) {
new Thread() {
@Override
public void run() {
while (true) {
if (holder != null) {
holder.assertSanity();
}
try {
Thread.sleep(1);
} catch (InterruptedException e) {
}
}
}
}.start();
}
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
}
initialize();
}
public void initialize() {
holder = new Holder(42);
}
}
但是没有任何不好的事情发生,没有抛出 AssertionError。
能否请您帮我弄清楚为什么这段代码不会阻止任何事情?
提前感谢您抽出宝贵时间。
【问题讨论】:
标签: java multithreading concurrency