public static Single getInstance() {
if (s == null) {
synchronized (Single.class) {
if (s == null)
s = new Single();
}
}
return s;
}
}
class SingleTest implements Runnable {
public void run() {
for (int x = 0; x < 30; x++) {
Single s = Single.getInstance();
System.out.println(s);
}
}
}
public class ThreadDemo4 {
public static void main(String[] args) {
SingleTest s = new SingleTest();
new Thread(s).start();
new Thread(s).start();
new Thread(s).start();
new Thread(s).start();
}
} 作者: a6511631 时间: 2014-8-19 23:57
网上流传的优化版,使用到了内部类,能保证延迟加载及多线程安全
public class Singleton {
/**
* 类级的内部类,也就是静态的成员式内部类,该内部类的实例与外部类的实例
* 没有绑定关系,而且只有被调用到才会装载,从而实现了延迟加载
*/
private static class SingletonHolder{
/**
* 静态初始化器,由JVM来保证线程安全
*/
private static Singleton instance = new Singleton();
}
/**
* 私有化构造方法
*/
private Singleton(){
}
public static Singleton getInstance(){
return SingletonHolder.instance;
}
}
复制代码
作者: fantacyleo 时间: 2014-8-20 01:22
用枚举,代码简洁、保证线程安全且不受反序列化的破坏。
public enum Single { INSTANCE }