java复现单例模式
时间: 2024-04-07 13:27:09 浏览: 13
在Java中,可以使用以下几种方式来实现单例模式:
1. 饿汉式:
```
public class Singleton {
private static Singleton instance = new Singleton();
private Singleton() {}
public static Singleton getInstance() {
return instance;
}
}
```
这种方式在类加载时就创建了实例,因此是线程安全的。
2. 懒汉式(非线程安全):
```
public class Singleton {
private static Singleton instance;
private Singleton() {}
public static Singleton getInstance() {
if (instance == null) {
instance = new Singleton();
}
return instance;
}
}
```
这种方式在第一次调用getInstance()方法时才创建实例,但是在多线程环境下可能会创建多个实例。
3. 懒汉式(线程安全,使用synchronized关键字):
```
public class Singleton {
private static Singleton instance;
private Singleton() {}
public static synchronized Singleton getInstance() {
if (instance == null) {
instance = new Singleton();
}
return instance;
}
}
```
这种方式通过给getInstance()方法加锁来保证线程安全,但是会影响性能。
4. 双重检查锁定(Double-Checked Locking):
```
public class Singleton {
private volatile static Singleton instance;
private Singleton() {}
public static Singleton getInstance() {
if (instance == null) {
synchronized (Singleton.class) {
if (instance == null) {
instance = new Singleton();
}
}
}
return instance;
}
}
```
这种方式在第一次调用getInstance()方法时才创建实例,并且通过双重检查锁定来保证线程安全和性能。