双重检验的单例模式如果没有加volitile,会有创建对象没有完成,其他线程已经过去到该对象的风险,请问通过代码怎么去证明?
请教一下,为什么没有加volitile,就会有线程获取到还没创建完成的对象呢?
...java
import java.util.concurrent.TimeUnit;
class Sun {
private Sun() {
}
private static Sun sun;
public static Sun getSun() {
if (sun == null) {
try {
TimeUnit.SECONDS.sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
sun = new Sun();
}
return sun;
}
}
public class SingleB {
public static void main(String[] args) {
for (int i = 0; i < 5; i++) {
new Thread(()->{
System.out.println(Sun.getSun().hashCode());
}).start();
}
for (int i = 0; i < 5; i++) {
new Thread(()->{
System.out.println(Sun.getSun().hashCode());
}).start();
}
}
}
...
你拿去运行一下,可以修改一下线程数量