单线程下可用
class Singleton {
private static Singleton singleton;
private Singleton(){
System.out.println("***************new Singleton***************");
}
public static Singleton getInstance() {
if (singleton == null) {
singleton = new Singleton();
}
return singleton;
}
public void print() {
System.out.println("Hello Singleton***************");
}
@Override
public String toString() {
return Singleton.class.getName();
}
}
class App {
public static void main(String[] args) {
Singleton instance = Singleton.getInstance();
instance.print();
}
}
多线程下(推荐)
class Singleton2 {
private static volatile Singleton2 singleton;
private Singleton2(){
System.out.println("***************new Singleton2***************");
}
public static Singleton2 getInstance() {
if (singleton == null) {
synchronized (Singleton2.class) {
if (singleton == null) {
singleton = new Singleton2();
}
}
}
return singleton;
}
public void print() {
System.out.println("Hello Singleton2***************");
}
@Override
public String toString() {
return Singleton2.class.getName();
}
}
class App2 {
public static void main(String[] args) {
for (int i = 0; i < 5; i++) {
new Thread(() -> Singleton2.getInstance().print(), "thread-" + i).start();
}
}
}