这段懒汉式应该synchronized前面使用双if在判断,否则会出现错误.
代码如下:
class Single{
private Single(){}
private static Single s=null;
public static Single getOop()
{
if (s == null)//如果已经赋值就直接返回return
{
synchronized(Single.class)
{
if (s == null)
{
try
{
Thread.sleep(20);
}
catch (Exception e)
{
}
s=new Single();
return s;
}
}
}
return s;
}
}
class Test implements Runnable{
public void run()
{
while(true)
{
Single s = Single.getOop();
System.out.println(s);
}
}
}
class Test5{
public static void main(String[] args){
Test t=new Test();
Thread t1=new Thread(t);
Thread t2=new Thread(t);
Thread t3=new Thread(t);
t1.start();
t2.start();
t3.start();
}
} |