饿汉式(线程不安全)java单例:
public class Hungry {
private static Hungry in= new Hungry();
private Hungry() {}
public static Hungry getIn() {
return instance;
}
}
懒汉式(线程不安全)java单例:
public class Idler {
private static Idler =null;
private Hungry() {}
public static Idler getIdler () {
if(instance==null) {
instance=new S1();
}
return instance;
}
}
双重检查(线程安全)java实例:
public class Singleton {
private static volatile Singleton singleton;
private Singleton() {}
public static Singleton getInstance() {
if (singleton == null) {
synchronized (Singleton.class) {
if (singleton == null) {
singleton = new Singleton();
}
}
}
return singleton;
}
}
枚举java单例(线程安全):
enum Color{
RED,GREEN,BLUE;
}
public class Hello {
public static void main(String[] args){
Color color=Color.RED;
int counter=10;
while (counter–>0){
switch (color){
case RED:
System.out.println(“Red”);
color=Color.BLUE;
break;
case BLUE:
System.out.println(“Blue”);
color=Color.GREEN;
break;
case GREEN:
System.out.println(“Green”);
color=Color.RED;
break;
}
}
}
}