求助单例双重锁定的验证
我之前还不知道这回事,把他当作经营共享了,还好火龙果指出了错误,这里表示感谢。
帖子在这。
http://topic.csdn.net/u/20090810/11/d3fd2c2e-0682-4f65-adf2-b908971b66eb.html
为了进一步弄清这个问题,我想求一个验证程序。我写了一个:
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package single;
/**
*
* @author l33187
*/
public class Single {
public static Single s = null;
public static Object lock = new Object();
private int a = 0;
private Single() {
this.a = 100;
}
public static Single getSingle() {
if (s == null) {
//synchronized (lock) {
if (s == null) {
//Single tmp = new Single();
//s = tmp;
s = new Single();
}
//}
}
return s;
}
public static void main(String[] args){
for(int i=0;i<50;i++){
Thread t = new Thread(new ThreadSingle());
t.start();
}
}
public static class ThreadSingle implements Runnable {
public void run() {
try {
int count =0;
for(int i=0;i<10;i++){//主要时混淆代码,让后续代码更多的机会并行
Thread.sleep(2);
}
if (Single.getSingle().a != 100){
System.out.println("!!!初始化失败!!!!");
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
但是很可惜行不通,甚至不加同步,还是初始化成功的。线程数从10改到1000都没验证出失败来。
请教达人验证方法。