题目是结论:
代码是测试用例,可自行通过修改注释切换单例与非单例
测试结果最后几行在 最下面.
package Thread;
import java.util.concurrent.CountDownLatch;
public class SingletonThreadSaveTest
{
private static SingletonThreadSaveTest ASTPMgr;
public static volatile int c = 0;
// public SingletonThreadSaveTest()
// {
//
// }
private SingletonThreadSaveTest(){}
public static SingletonThreadSaveTest getInstance()
{
if(ASTPMgr == null)
{
synchronized(SingletonThreadSaveTest.class)
{
if(ASTPMgr == null){
ASTPMgr = new SingletonThreadSaveTest();
}
}
}
return ASTPMgr;
}
public void add()
{
for (int i = 0; i < 10000; i++)
{
c++;
Thread current = Thread.currentThread();
System.out.println("Id:" + current.getId() +"Add:" + String.valueOf(c)+ " Name:" + current.getName() + " activeCount:" + Thread.active