public class FaceObject implements Serializable {//让单例类可以被序列化
public static void main(String[] args) {
Singleton s = Singleton.getInstance();
s.method();
Singleton s2 = Singleton.getInstance();
s2.method();
System.out.println(s == s2);
int i =Math.max(0,127);
System.out.println(i);
}
//饿汉模式单例
static class Singleton {
private Singleton(){}//构造方法私有化
private static Singleton s =new Singleton();//创建本类对象
private static Singleton getInstance(){//提供一个获取本类对象的方法(私有并且静态)
return s;
}
public void method(){
System.out.println("饿汉单例模式运行");
}
}
//懒汉模式单例
static class Singleton2 {
private Singleton2() {
if(s2!=null){//防止反射调用私有构造方法
throw new RuntimeException("此类对象为单例模式,已经被实例化了");
}
}
private volatile static Singleton2 s2=null;//加上volatile关键字保证变量的一致性
private static Singleton2 getInstance() {
//双重判断解决多线程问题
if (s2 == null) {//第一次判断是判断是否已经创建了对象
synchronized (Singleton2.class) {//加锁,解决线程安全的问题
if (s2 == null) {//是抢到第一次cpu时间片的线程用来判断是否已经创建对象
s2 = new Singleton2();
}
}
}
return s2;
}
}
}