java 饿汉试
package com.single2.instance;
//饿汉式
public class Comany {
//单例三大件
private static Comany comany = new Comany();
1 | |
}
package com.single2.instance;
//懒汉式
public class Dept {
private static Dept dept;
1 | |
}
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 | |
}
java 饿汉试
http://example.com/java-饿汉试.html