前言:直接介绍几种线程安全的且我觉得还比较不错的方式:
1.
public class Singleton
{
private static Singleton instance = new Singleton();
public static Singleton getInstance()
{
return instance ;
}
}
2、懒汉
public class Singleton02
{
private static Singleton02 instance;
public static Singleton02 getInstance()
{
if (instance == null)
{
synchronized (Singleton02.class)
{
if (instance == null)
{
instance = new Singleton02();
}
}
}
return instance;
}
}
3、使用一个持有类,主要是为了不在初始化的时候加载
public class Singleton04
{
private static final class InstanceHolder
{
private static Singleton04 INSTANCE = new Singleton04();
}
public static Singleton04 getInstance()
{
return InstanceHolder.INSTANCE;
}
}
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。
文章由半码博客整理,本文链接:https://www.bmabk.com/index.php/post/12866.html