你作为一个Java领域的专家,请完成以下任务:手写尽可能多的单例模式,线程安全不安全都可以
时间: 2024-05-07 10:21:56 浏览: 91
6单例模式的实现及是否线程安全
1. 饿汉式(线程安全)
```
public class Singleton {
private static final Singleton INSTANCE = new Singleton();
private Singleton(){}
public static Singleton getInstance(){
return INSTANCE;
}
}
```
2. 懒汉式(线程不安全)
```
public class Singleton {
private static Singleton INSTANCE = null;
private Singleton(){}
public static Singleton getInstance(){
if(INSTANCE == null){
INSTANCE = new Singleton();
}
return INSTANCE;
}
}
```
3. 懒汉式(线程安全,同步方法)
```
public class Singleton {
private static Singleton INSTANCE = null;
private Singleton(){}
public static synchronized Singleton getInstance(){
if(INSTANCE == null){
INSTANCE = new Singleton();
}
return INSTANCE;
}
}
```
4. 懒汉式(线程安全,双重校验锁)
```
public class Singleton {
private static volatile Singleton INSTANCE = null;
private Singleton(){}
public static Singleton getInstance(){
if(INSTANCE == null){
synchronized(Singleton.class){
if(INSTANCE == null){
INSTANCE = new Singleton();
}
}
}
return INSTANCE;
}
}
```
5. 静态内部类(线程安全)
```
public class Singleton {
private Singleton(){}
private static class SingletonHolder{
private static final Singleton INSTANCE = new Singleton();
}
public static Singleton getInstance(){
return SingletonHolder.INSTANCE;
}
}
```
6. 枚举(线程安全)
```
public enum Singleton {
INSTANCE;
public void doSomething(){
//...
}
}
```
阅读全文