package SingletonTest;
class Singleton{
private volatile static Singleton instance;
private Singleton(){
}
public static Singleton getInstance(){
if(instance == null){
synchronized (Singleton.class) {
if(instance == null){
instance = new Singleton();
}
//instance = new Singleton();
}
}
return instance;
}
}
public class MyThread extends Thread{
@Override
public void run(){
System.out.println(Singleton.getInstance().hashCode());
}
public static void main(String[] args){
MyThread[] myThread = new MyThread[10];
for(int i=0;i<myThread.length;i++){
myThread[i] = new MyThread();
}
for(int i=0;i<myThread.length;i++){
myThread[i].start();
}
}
}
双重锁的运行结果:
1156205522
1156205522
1156205522
1156205522
1156205522
1156205522
1156205522
1156205522
1156205522
1156205522
去掉第二重锁的运行结果(产生了多例):
1700548907
1486202908
1486202908
1700548907
1486202908
1486202908
1700548907
1486202908
1486202908
1700548907