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 Single getInstance(){
if(s==null)
//在多线程下执行if语句后进行休眠状态时就会造成单例模式破坏(单例只对应一个对象),就会创建多个对象
s=new Single;
return s;
}
}
class Demo implements Runnable
{
public void run()
{
single.getInstance();
}
}
|
|