标签:logs sync 读取内容 分享 get on() 代码块 校验 tin
public class Singleton { private static Singleton instance; private Singleton(){} public static Singleton getInstance(){ if(instance == null){ instance = new Singleton(); } return instance; } }
public class Singleton { private static Singleton instance = new Singleton(); private Singleton(){} public static Singleton getInstance(){ return instance; } }
public class Singleton { private static class SingletonHolder { private static final Singleton INSTANCE = new Singleton(); } private Singleton(){} public static final Singleton getInstance(){ return SingletonHolder.INSTANCE; } }
public enum Singleton { INSTANCE; //这里也可以写一些这个类的其他方法.. }
7.双重校验锁
public class Singleton { private volatile static Singleton singleton; private Singleton() {} public static Singleton getSingleton() { if (singleton == null) { synchronized (Singleton.class) { if (singleton == null) { singleton = new Singleton(); } } } return singleton; } }
public static void main(String[] args) throws IOException, ClassNotFoundException{ FileOutputStream fos = new FileOutputStream("tempFile"); ObjectOutputStream output = new ObjectOutputStream(fos); //将对象序列化写出到文件 output.writeObject(Singleton.getInstance()); output.close(); //从文件中读取内容反序列化为对象 FileInputStream fis = new FileInputStream("tempFile"); ObjectInputStream input = new ObjectInputStream(fis); Singleton newSingleton = (Singleton) input.readObject(); System.out.println(newSingleton == Singleton.getInstance()); /*比较获得的结果是false,代表这是两个不同的对象*/ input.close(); //删除临时文件 File file = new File("tempFile"); if(file.delete()){ System.out.println("文件删除成功"); } }
标签:logs sync 读取内容 分享 get on() 代码块 校验 tin
原文地址:http://www.cnblogs.com/programInit/p/6363176.html