阿凡达ml
2017-12-23 17:06:07
java线程安全的单列模式(4种)
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; } }
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;//返回一个类的静态对象,只有调用这语句内部类才会初始化,所以能实现赖加载 } }
评论