synchronized (classname.getClass()) 的编程习惯

    前端时间总是有人问同步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();
	}
}


 

  这样两个对象之间的获取便产生了冲突,但这种方式在特定情况是非常适用的,作为一般多线程编程来讲,还是少写getclass为妙。
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值