java 懒汉式、饿汉式单例模式 含多线程的情况
//饿汉式 提前生成了单例对象 class Singleton{ private static final Singleton instance=new Singleton(); private Singleton(){} public static Singleton getInstance(){ return instance; } } //懒汉式 调用的时候才会生成对象 class Singleton11 { private static Singleton11 instance; private Singleton11(){} public static Singleton11 getInstance(){ if (instance==null) { instance=new Singleton11(); } return instance; } } //多例模式 class Color { private static final Color Red=new Color("红色"); private static final Color Green=new Color("绿色"); private static final Color Blue=new Color("蓝色"); private String color; private Color(String color){ this.color=color; } public static Color getInstance(String color){ switch (color) { case "红色": return Red; case "绿色": return Green; case "蓝色": return Blue; default: return null; } } public String print(){ return this.color; } } public class TestSingleton{ public static void main(String[] args){ Singleton A=Singleton.getInstance(); Singleton B=Singleton.getInstance(); System.out.println(A==B); Singleton11 A11=Singleton11.getInstance(); Singleton11 B11=Singleton11.getInstance(); System.out.println(A11==B11); Color red=Color.getInstance("红色"); Color green=Color.getInstance("绿色"); Color blue=Color.getInstance("蓝色"); System.out.println(red.print()); System.out.println(green.print()); System.out.println(blue.print()); } }
多线程的情况:
class Singleton{ private static volatile Singleton instance=null; //直接操作主内存 比操作副本效果好 private Singleton(){ System.out.println(Thread.currentThread().getName()+"******实例化Singleton******"); } public static Singleton getInstance(){ if (instance==null){ synchronized (Singleton.class){ //此处同步的是new Singleton() 提升多线程效率 if (instance==null){ //此处的判断 对应上面的if (instance==null) 多个线程进来 instance=new Singleton(); } } } return instance; } public void print(){ System.out.println("wwww.mldn.com"); } } public class SingleInstance { public static void main(String[] args) { // Singleton s=Singleton.getInstance(); // s.print(); // Singleton ss=Singleton.getInstance(); // ss.print(); // System.out.println(s==ss); for (int i=0;i<3;i++){ new Thread(()-> System.out.println(Singleton.getInstance()),"单例"+i).start(); } } }