有毛病的单例2

import java.io.FileNotFoundException;
import java.io.PrintStream;
import java.util.ArrayList;
import java.util.List;

class Ta
{
	static Ta instance = null;

	static Object locker = new Object();

	private Ta()
	{
	}

	public static Ta getInstance()
	{
		System.out.println("==进来了!");
		if (instance != null)
		{
			System.out.println("不空,直接返回了。");
			return instance;
		}
		try
		{
			System.out.println("马上开始制造了!");
			Thread.sleep(100);
		}
		catch (InterruptedException e)
		{
			e.printStackTrace();
		}

		System.out.println("先锁住。");
		synchronized (locker)
		{
			System.out.println("进锁里了");
			if (instance != null)
			{
				System.out.println("锁里不空,返回了。");
				return instance;
			}
			System.out.println("在锁里开始制造了!");
			instance = new Ta();
			System.out.println("在锁里造好了!");
			return instance;
		}
	}

}

public class Test
{
	private static boolean flag = true;
	static
	{
		try
		{
			System.setOut(new PrintStream("D:\\zz.txt"));
		}
		catch (FileNotFoundException e)
		{
			e.printStackTrace();
		}
	}
	
	public static void main(String[] args)
	{
		final List<Ta> list = new ArrayList<Ta>();
		while (flag)
		{
			new Thread(new Runnable()
			{
				public void run()
				{
					//TODO 重新赋值
					Ta.locker = new Object();
					try
					{
						Thread.sleep(6);
					}
					catch (InterruptedException e)
					{
						e.printStackTrace();
					}
					Ta t = Ta.getInstance();
					
					int len = 300;
					if(list.size()< len)
						list.add(t);
					else
					{
						flag = false;
						Ta ta = list.get(0);
						for(int i = 1; i < len; i ++)
						{
							boolean b = ta == list.get(i);
							if(!b)
								System.out.println("=================================================================不一样了!");
						}
					}
				}
			}).start();
		}
	}
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值