单例懒汉式
class Single
{
private static Single s1= null;
private Single(){}
public static Single insTance()
{
if(s1==null)
{
Single s1 = new Single();
}
return s1;
}
}
如果涉及到多线程就要考虑安全
饿汉式不涉及安全问题所以主要是懒汉式
懒汉式多线程安全问题解决
如下
class Single
{
private static Single s1= null;
private Single(){}
public static Single insTance()
{
synchronized(Single.class)//因为多线程同时操作数据是两条所以不安全,要加同步代码块
{
if(s1==null)
{
Single s1 = new Single();
}
return s1;
}
}
}
如何让懒汉式更高效呢
如下
class Single
{
private static Single s1= null;
private Single(){}
public static Single insTance()
{
if(s1==null)//为了提高效率所以在这里就判断一下,不然每次都要判断锁。因此提高了效率
{
synchronized(Single.class)
{
if(s1==null)
{
Single s1 = new Single();
}
}
}
return s1;
}
}
|
|