1 package com.jdk7.chapter2.singleton; 2 3 public class SingletonA { 4 //java虚拟机会加载静态变量 5 private static int id = 1; 6 private static SingletonA instance = new SingletonA(); 7 8 //私有构造函数,不被其他类调用创建类的对象 9 private SingletonA(){}10 11 //同步获取id值,同一时刻只有一个线程进入该方法12 public synchronized int getId() {13 return id;14 }15 16 public synchronized int next(){17 return id++;18 }19 //在其他类中只能调用类名+getInstance方法获取类的对象20 public static SingletonA getInstance() {21 return instance;22 };23 }
1 package com.jdk7.chapter2.singleton; 2 3 public class SingletonB { 4 //java虚拟机会加载静态变量 5 private static int id = 1; 6 private static SingletonB instance = null; 7 8 //私有构造函数,不被其他类调用创建类的对象 9 private SingletonB(){}10 11 //同步获取id值,同一时刻只有一个线程进入该方法12 public synchronized int getId() {13 return id;14 }15 16 public synchronized int next(){17 return id++;18 }19 20 //只创建一次对象,提供给后面每次使用21 public static SingletonB getInstance() {22 if(instance==null){23 instance = new SingletonB();24 }25 return instance;26 }27 }
1 package com.jdk7.chapter2.singleton; 2 3 public class SingleTest { 4 public static void main(String[] args) { 5 System.out.println("调用next方法前"); 6 SingletonA single1 = SingletonA.getInstance(); 7 SingletonA single2 = SingletonA.getInstance(); 8 System.out.println("single1: "+single1); 9 System.out.println("single2: "+single2);10 System.out.println("single1: "+single1.getId());11 System.out.println("single2: "+single2.getId());12 single1.next();13 System.out.println("调用next方法后");14 System.out.println("single1: "+single1.getId());15 System.out.println("single2: "+single2.getId());16 17 SingletonB b1 = SingletonB.getInstance();18 SingletonB b2 = SingletonB.getInstance();19 System.out.println("调用next方法前");20 System.out.println("b1: "+b1);21 System.out.println("b2: "+b2);22 System.out.println("b1: "+b1.getId());23 System.out.println("b2: "+b2.getId());24 System.out.println("调用next方法后");25 b1.next();26 System.out.println("b1: "+b1.getId());27 System.out.println("b2: "+b2.getId());28 }29 }30 31 执行结果:32 调用next方法前33 single1: com.jdk7.chapter2.singleton.SingletonA@64b6be6934 single2: com.jdk7.chapter2.singleton.SingletonA@64b6be6935 single1: 136 single2: 137 调用next方法后38 single1: 239 single2: 240 调用next方法前41 b1: com.jdk7.chapter2.singleton.SingletonB@32728d42 b2: com.jdk7.chapter2.singleton.SingletonB@32728d43 b1: 144 b2: 145 调用next方法后46 b1: 247 b2: 2
1 package com.jdk7.chapter5; 2 3 public class Single { 4 //私有的静态对象 5 private static Single Instance = new Single(); 6 7 //私有的无参构造函数,在该类中可以new对象,但是在其他类中不可以new对象,保证了对象的唯一性 8 private Single(){} 9 10 //仅对外开放Instance变量的getter方法11 public static Single getInstance() {12 return Instance;13 }14 15 public static void main(String[] args) {16 Single s = new Single();17 System.out.println("s.hashcode>"+s.hashCode());18 System.out.println(Single.getInstance());19 System.out.println(Single.getInstance());20 }21 }22 23 执行结果:24 s.hashcode>67256894825 com.jdk7.chapter5.Single@62efae3b26 com.jdk7.chapter5.Single@62efae3b