单例模式分为懒汉式和饿汉式
public class Singleton {
/**
* 饿汉式,线程安全
*/
private static Singleton singleton = new Singleton();
private Singleton(){
}
public static Singleton getInstance(){
return singleton;
}
public static void main(String[] args) {
System.out.println(Singleton.getInstance() == Singleton.singleton);
}
}
"D:\Program Files\Java\jdk1.8.0_102\bin\java.exe" ...
true
懒汉式
public class Singleton {
/**
* 懒汉式,线程不安全
*/
private static Singleton singleton = null;
private Singleton(){
}
public static Singleton getInstance(){
if(singleton == null){
singleton = new Singleton();
}
return singleton;
}
public static void main(String[] args) {
System.out.println(Singleton.getInstance() == Singleton.singleton);
}
}
// 懒汉式对于高并发时,线程A线程B同时请求到if判断时候会创建出两个实例,就会导致单例失效
public class Singleton {
/**
* 懒汉式,线程不安全
*/
private static Singleton singleton = null;
private Singleton(){
}
// 给方法加锁可以解决并发带来问题
public static synchronized Singleton getInstance(){
if(singleton == null){
singleton = new Singleton();
}
return singleton;
}
public static void main(String[] args) {
System.out.println(Singleton.getInstance() == Singleton.singleton);
}
}
// 加载类时候提前初始化,这样可以避免线程不安全问题
public class Singleton {
/**
* 懒汉式,线程安全
*/
private static Singleton singleton = null;
// 提前初始化
static {
singleton = new Singleton();
}
private Singleton() {
}
public static Singleton getInstance() {
return singleton;
}
public static void main(String[] args) {
System.out.println(Singleton.getInstance() == Singleton.singleton);
}
}
public class Singleton {
/**
* 懒汉式,线程安全
*/
private static Singleton singleton = null;
private Singleton() {
}
// 给对象加锁,可以有效避免线程不安全
public static Singleton getInstance() {
synchronized (Singleton.class) {
if (singleton == null) {
singleton = new Singleton();
}
}
return singleton;
}
public static void main(String[] args) {
System.out.println(Singleton.getInstance() == Singleton.singleton);
}
}
public class Singleton {
private final static class InnerSingleton {
private static final Singleton SINGLETON = new Singleton();
}
private Singleton() {
}
// 采用内部类可以有效避免线程不安全
public static Singleton getInstance() {
return InnerSingleton.SINGLETON;
}
public static void main(String[] args) {
System.out.println(Singleton.getInstance() == InnerSingleton.SINGLETON);
}
}
// 使用双重重入锁解决单例模式线程不安全问题
public class Singleton {
private volatile static Singleton singleton = null;
private Singleton() {
}
public static Singleton getInstance() {
synchronized (Singleton.class) {
if (singleton == null) {
singleton = new Singleton();
}
}
return singleton;
}
public static void main(String[] args) {
System.out.println(Singleton.getInstance() == Singleton.singleton);
}
}