public class DanLi { private DanLi() { } private static DanLi d1=null; public static DanLi instance() { if(d1==null) { d1=new DanLi(); } return d1; } private int m=0; public void run() { for(int i=0;i<10;i++) { m++; System.out.println("m="+m); } } public static void main(String[] args) { System.out.println("t1单例"); DanLi t1=DanLi.instance(); t1.run(); System.out.println("t2单例"); DanLi t2=DanLi.instance(); t2.run(); } }
public class DanLi2 { private DanLi2() { } private final static DanLi2 t1=new DanLi2(); public static DanLi2 instance() { return t1; } private int m=0; public void run() { for(int i=0;i<10;i++) { m++; System.out.println("m="+m); } } public static void main(String[] args) { System.out.println("t1单例"); DanLi t1=DanLi.instance(); t1.run(); System.out.println("t2单例"); DanLi t2=DanLi.instance(); t2.run(); } }