java 饿汉试

package com.single2.instance;

//饿汉式

public class Comany {
//单例三大件
private static Comany comany = new Comany();

1
2
3
4
5
6
7
//构造器,创建对象时候用
private Comany(){}

//工具类的方法我们一般都是静态
public static Comany getInstance(){
return comany;
}

}

package com.single2.instance;

//懒汉式

public class Dept {
private static Dept dept;

1
2
3
4
5
6
7
8
9
10
private Dept(){}

public static Dept getDept(){
//对象在需要时候才创建。这个是和饿汉式根本的区别
//只有第一次调用时候创建对象,因为还没有这个对象,以后都不需要再创建。
if(dept == null){
dept = new Dept();
}
return dept;
}

}

package com.single2.instance;
/**

  • CPU运行是资源抢占式
    *
    */
    public class Group {
    private static Group group; private Group(){} public static synchronized Group getGroup(){
    if(group == null){
    group = new Group();
    }
    return group;
    }
    }

测试

package com.single2.test;

import com.single2.instance.Comany;
import com.single2.instance.Dept;
//边写边保存边测试
//ctrl+s保存
public class Test {
//所有测试代码放到Main方法,因为这是程序的入口
public static void main(String[] args) {
//所有测试代码
Comany c1 = Comany.getInstance();
Comany c2 = Comany.getInstance();
System.out.println(c1 == c2);

1
2
3
4
    Dept d1 = Dept.getDept();
Dept d2 = Dept.getDept();
System.out.println(d1 == d2);
}

}


java 饿汉试
http://example.com/java-饿汉试.html
作者
John Doe
发布于
2021年5月14日
许可协议