前端时间总是有人问同步synchronized的问题,许多人遇到这样的问题总是多线程情况的单例模式中。有的人是这样写他的单例的
class Test5{
private Test5(){}
private static Test5 instance=null;
public static Test5 getInstance(){
if(instance==null){
synchronized (instance.getClass())
{
if(instance==null)
instance=new Test5();
return instance;
}
}
return instance;
}
}
这样写的话,是肯定有问题的instance为空,会有空指针报错。个人认为应该在单例模式中另添加一个Boolean型的flag,作为高效产生与获得单例的方式。但问题主要不是这里,遇到的问题不仅仅于此,而在于getClass方法,获取的Class对象为所有对象共有的,所以同步块中经常使用getclass方法很不安全(单例模式倒是例外,因为其一个Class只对应于一个对象),例如:
public class Test4
{
Integer b1 = new Integer(123);
Integer b2 = new Integer(124);
public Test4()
{
Thread t1 = new Thread(new RUN(b1));
Thread t2 = new Thread(new RUN1(b2));
t1.start();
java.awt.EventQueue.invokeLater(t2);
}
private static class RUN implements Runnable
{
Integer b = null;
RUN(Integer b)
{
this.b = b;
}
@Override
public void run()
{
synchronized (b.getClass())
{
try
{
Thread.sleep(5000);
} catch (InterruptedException e)
{
e.printStackTrace();
}
}
}
}
private static class RUN1 implements Runnable
{
Integer b = null;
RUN1(Integer b)
{
this.b = b;
}
@Override
public void run()
{
synchronized (b.getClass())
{
System.out.println(b);
}
}
}
public static void main(String[] args)
{
new Test4();
}
}