package test;
public class Tiger6 {
static class Inner {
private static Inner instance = null;
private Inner() { //每调用一次构造函数,打印一条消息。
System.out.println("create a Inner object!");
}
public static Inner getInstance() {
if (instance == null) {
instance = new Inner();
}
return instance;
}
}
public static void main(String[] args) {
Thread[] ts = new Thread[100];
for (int i = 0; i < ts.length; i++) {
ts[i] = new Thread(
new Runnable() {
public void run() {
Inner.getInstance();
}
}
);
}
for (Thread t : ts) {
t.start();
}
}
}
结果:
create a Inner object!
create a Inner object!
create a Inner object!
显然,结果是违反单例模式要求的。
现在在Inner.getInstance()方法上加上synchronized。
结果:
create a Inner object!
当然还有另外一种办法:
public static Inner getInstance() {
synchronized(Inner.class) {
if (instance == null) {
instance = new Inner();
}
}
return instance;
}
分析:通过上面这种办法,可以控制在同一时刻上,只允许有一个线程访问到变量instance。
return instance;
}
分析:通过上面这种办法,可以控制在同一时刻上,只允许有一个线程访问到变量instance。
当然,只有对懒汉式单例模式才有这个问题。对于饿汉式单例模式,Inner对象在类装载时就被创建。