gpt4 book ai didi

java - 线程安全惰性初始化实现单例的两种方式

转载 作者:行者123 更新时间:2023-11-29 07:49:05 26 4
gpt4 key购买 nike

静态方法和变量:

public class Singleton{

private static Singleton singleton = null;

private Singleton(){
}

public static synchronized Singleton getInstance(){
if(singletion == null)
singleton = new Singletion();
return singleton;
}
}

Java 1.5 之后的第二个

public class Singleton{

private static volatile Singleton singleton = null;

private Singleton(){
}

public static Singleton getInstance(){
if(singleton == null){
synchronized(this){
if(singleton == null){
singleton = new Singleton();
}
}
}
return singleton;
}
}

那么这两种线程安全代码的优缺点是什么,我们应该在什么时候使用哪一种?

最佳答案

第二个是线程安全的,但下面的更简单,更快,因为它不需要同步块(synchronized block)。

public enum Singleton {
INSTANCE;
// define fields and methods here.
}

访问

Singleton.INSTANCE.method();

注意:如果需要,枚举可以实现接口(interface)。

关于java - 线程安全惰性初始化实现单例的两种方式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22749162/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com