您的位置:首页 > 其它

线程安全的单列模式(4种)

2017-11-09 21:10 337 查看
1.不使用同步锁

public class Singleton {

private static Singleton s = new Singleton();//直接初始化一个实例对象

private Singleton() {///private类型的构造函数,保证其他类对象不能直接new一个该对象的实例
System.out.println("Singleton");
}

public static Singleton getSingle() {//该类唯一的一个public方法
return s;
}

}
上述代码中的一个缺点是该类加载的时候就会直接new 一个静态对象出来,当系统中这样的类较多时,会使得启动速度变慢 。现在流行的设计都是讲“延迟加载”,我们可以在第一次使用的时候才初始化第一个该类对象。所以这种适合在小系统。

2.使用同步方法

public class Singleton {

private static Singleton instance;

private Singleton() {}

public static synchronized Singleton getIntance() {//对获取实例的方法进行同步
if(instance == null) {
instance = new Singleton();
}
return instance;
}
}


上述代码中的一次锁住了一个方法, 这个粒度有点大 ,改进就是只锁住其中的new语句就OK。就是所谓的“双重锁”机制。

3.使用双重同步锁

public class Singleton {

private static Singleton instance;
private Singleton() {}

public static Singleton getInstance() {
if(instance == null) {
synchronized (Singleton.class) {
if(instance == null) {
instance = new Singleton();
}
}
}
return instance;
}

}


4.使用内部类,既不用加锁,也能实现懒加载

public class Singleton4 {

private Singleton4() {
System.out.println("single");

}

private static class Inner {
private static Singleton4 s = new Singleton4();
}

public static Singleton4 getSingle() {
return Inner.s;//返回一个类的静态对象,只有调用这语句内部类才会初始化,所以能实现赖加载
}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: