标签:style java学习 java this syn int 创建对象 div 一个
class Single { /** 方式一、饿汉式 开发建议使用 */ //1.将构造函数私有化 private Single(){} //2.在类中创建对象 private static Single s=new Single(); //3.提供一个方法用于获取此类对象 public static Single getInstance() { return s; } /** 方式二、懒汉式 */ private Single(){} private static Single s=null; //线程不安全 public static Single getInstance() { if(s==null) s=new Single(); return s; } //加同步(效率低) public static synchronized Single getInstance() { if(s==null) s=new Single(); return s; } //双重判断 public static Single getInstance() { if(s==null) { synchronized(Single.class) { if(s==null) s=new Single(); } } return s; } private int num; public int getNum() { return num; } public void setNum(int num) { this.num=num; } } class SingleDemo { public static void main (String[] args) { Single s1=Single.getInstance(); Single s2=Single.getInstance(); s1.setNum(23); System.out.println(s2.getNum()); } }
标签:style java学习 java this syn int 创建对象 div 一个
原文地址:https://www.cnblogs.com/WarBlog/p/12054282.html