关于 volatile 修饰在数组上的可见性问题

chenchengamao chenchengamao 墨衍会员 · AI 创作全网分发 墨衍智能分发 通过墨衍一键同步至各平台 可同步平台 CSDN微信公众号微博知乎掘金百家号博客园抖音小红书 你的文章也可以这样分发 墨衍会员 ¥399起/年,写一次发全网 我也要 + 加入社区
使用 volatile 修饰符时,大家都知道被它修饰的属性都有可见性的特性,如果将 volatile 修饰在数组上,按我的理解是:它只对引用这个数组的属性本身有效,而对这个数组里面引用的对象,是没有效果的。但是现在问题来了,我在做试验时,发现在它对数组里面引用的对象也有效果,我的代码如下,大家帮忙看看是什么原因。



代码一:

public class Test {

private String name;

public Test(String name) {
this.name = name;
}

public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}

}



代码二:

public class MyJava {

public static final int SIZE = 1000;
private volatile Test[] testArray = new Test[SIZE];

public MyJava() {
for (int i = 0; i < SIZE; i++) {
testArray[i] = new Test("name:" + i);
}
}
public static void main(String[] args) {
new InitThread(new MyJava()).start();
}
public Test getTest(int index) {
return testArray[index];
}
public void setTest(int index, Test t) {
testArray[index] = t;
}

}



代码三:

import java.util.Random;

public class InitThread extends Thread {

private MyJava mj;

public InitThread(MyJava mj) {
this.mj = mj;
}

public void run() {
int at = new Random().nextInt(MyJava.SIZE);
for (int i = 0; i < 10; i++) {
new MonitorThread("线程:" + i, mj, at).start();
}
try {
Thread.sleep(3000);
} catch (Exception e) {
}
Test t = mj.getTest(at);
t.setName("测试");
}

}



代码四:

public class MonitorThread extends Thread {

private MyJava mj;
private int at;

public MonitorThread(String name, MyJava mj, int at) {
super(name);
this.mj = mj;
this.at = at;
}

public void run() {
while (true) {
Test t = mj.getTest(at);
if ("测试".equals(t.getName())) break;
}
System.out.println(getName() + " over");
}

}




测试结果:
在代码二中,如果 testArray 属性有加 volatile ,那么代码四的线程会执行完,如果把 testArray 属性的 volatile 拿掉,那么代码四的线程就永远执行不完。
按道理说 testArray 属性不讨是有加 volatile 还是没加 volatile ,代码四都应该永远执行不完才对,现在变成有加 volatile 会执行完,这是什么原因?



...全文
评论 1
收藏 已收藏
分享
返回顶部
chenchengamao
Java SE 62,621 成员 307,251 内容