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();
}
}
}
有毛病的单例2
最新推荐文章于 2024-04-22 10:57:40 发布