public class Singleton {
public static void main(String[] args) {
Singleton s1 = Singleton.getInstance();
Singleton s2 = Singleton.getInstance();
System.out.println(s1 == s2);
}
private static Singleton instance;
/**将构造器使用private修饰,隐藏该构造器**/
private Singleton(){
System.out.println("Singleton被构造!");
}
/**线程安全,但性能有待优化,这样写每次调用getInstance方法都需要同步。
实际上只是第一次加载需要同步**/
public static synchronized Singleton getInstance() {
if (instance == null) {
instance = new Singleton();
}
return instance;
}
}
public class Singleton2 {
/**注意volatile的修饰,有待改进吧**/
private static Lock lock=new ReentrantLock();
private static volatile Singleton2 uniqueInstance;
private Singleton2() {
}
public static void main(String[] args) {
Singleton2 s1 = Singleton2.getInstance();
Singleton2 s2 = Singleton2.getInstance();
System.out.println(s1 == s2);
} public static Singleton2 getInstance() {
if(uniqueInstance == null) {
lock.lock();
try {
/**double check**/
if(uniqueInstance == null)
uniqueInstance = new Singleton2();
}catch (Exception e){
}finally {
lock.unlock();
}
}
return uniqueInstance;
}
}
public class SingletonTest {
/**注意volatile关键字,这个方法还是不错的**/
private static volatile SingletonTest instance = null; private SingletonTest() {
} public static void main(String[] args) {
SingletonTest s1 = SingletonTest.getInstance();
SingletonTest s2 = SingletonTest.getInstance();
System.out.println(s1 == s2);
} private static synchronized void syncInit() {
if (instance == null) {
instance = new SingletonTest();
}
} public static SingletonTest getInstance() {
if (instance == null) {
syncInit();
}
return instance;
}
}
public class Singleton_thread {
/**私有构造方法,防止被实例化**/
private Singleton_thread() {
} public static void main(String[] args) {
Singleton_thread s1 = Singleton_thread.getInstance();
Singleton_thread s2 = Singleton_thread.getInstance();
System.out.println(s1 == s2);
} /**此处使用一个内部类来维护单例,类的加载线程互斥**/
private static class SingletonFactory {
private static Singleton_thread instance = new Singleton_thread();
} /**获取实例**/
public static Singleton_thread getInstance() {
return SingletonFactory.instance;
} }
05-08 08:20