您的位置:首页 > 其它

(多线程-单例设计模式-懒汉式)

2015-10-13 17:45 369 查看
/*
单例设计模式。
饿汉式  --->  常用
懒汉式 --->
区别:
懒汉式:延迟加载,但会出现安全问题,解决方法加同步(synchronized)同步代码块与同步函数都行,但稍微有点低效。用双重判断的方法可以解决效率问题。
加同步是使用的锁是该类的字节码对象 即 : 类名.class

*/
//饿汉式。
/*
class Single
{
private static final Single s = new Single();
private Single(){}
public static Single getInstance()
{
return s;
}
}
*/

//懒汉式

class Single
{
private static Single s = null;
private Single(){}

/*
public static synchronized Single getInstance()
{
if(s==null)
s = new Single();
return s;
}
*/

public static  Single getInstance()
{
if(s==null)
{
synchronized(Single.class)
{
if(s==null)
//--->A;
s = new Single();
}
}
return s;
}
}

class SingleDemo
{
public static void main(String[] args)
{
System.out.println("Hello World!");
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: