用java写一个线程安全的单例饿汉模式
时间: 2023-05-28 10:05:56 浏览: 94
java多线程之线程安全的单例模式
public class Singleton {
private static final Singleton INSTANCE = new Singleton();
private Singleton() {
}
public static Singleton getInstance() {
return INSTANCE;
}
}
// 使用 synchronized 关键字实现线程安全的单例饿汉模式
public class Singleton {
private static Singleton INSTANCE;
private Singleton() {
}
public static synchronized Singleton getInstance() {
if (INSTANCE == null) {
INSTANCE = new Singleton();
}
return INSTANCE;
}
}
阅读全文