Singleton(單例模式)的使用和測試效率

測試時一個一個試

/**
 * @version
 * @description
 */
package cn.xasmall.example;


/**
 * @author 26248
 *
 */
public class TestSingleton{
    private String name=null;
//  懶漢模式(存在線程安全問題)
    private static TestSingleton testSingleton=null;
    //餓漢模式(不存在線程安全問題)
//  private static TestSingleton testSingleton=new TestSingleton();
    private TestSingleton() {

    }
//  懶漢模式
//  public static TestSingleton getInstance() {
//      if(testSingleton==null)
//          testSingleton=new TestSingleton();
//      return testSingleton;
//  }
//  餓漢模式
//  public static TestSingleton getInstance() {
//      return testSingleton;
//  }
    //解決懶漢模式線程安全問題
//  synchronized public static TestSingleton getInstance() {
//      if(testSingleton==null)
//          testSingleton=new TestSingleton();
//      return testSingleton;
//  }
    //double-check(雙重檢測)
    public static TestSingleton getInstance() {
        if(testSingleton!=null) {

        }
        else {
            synchronized (TestSingleton.class) {
                if(testSingleton==null)
                    testSingleton=new TestSingleton();
            }
        }
        return testSingleton;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name=name;
    }
}
//  //內部類
//public class TestSingleton{
//  private static class SingleHoder{
//      private static final TestSingleton singleton=new TestSingleton();
//  }
//  private TestSingleton() {
//      
//  }
//  public static final TestSingleton getInstance() {
//      return SingleHoder.singleton;
//  }
//}
//枚舉(不是很理解)
//public enum TestSingleton{
//  INSTANCE;
//  public void leaveTheBuilding() {
//      
//  }
//}
/**
 * @version
 * @description
 */
package cn.xasmall.example;

/**
 * @author 26248
 *
 */
public class TestThreadSingleton implements Runnable {
    public TestThreadSingleton() {

    }
    public void run() {
//      System.out.println(TestSingleton.INSTANCE.hashCode());
        System.out.println(TestSingleton.getInstance().hashCode());
    }

}
/**
 * @version
 * @description
 */
package cn.xasmall.example;

/**
 * @author 26248
 *
 */
public class TestSingletonmain {
    //測試時間
    public static void main(String[] args) throws Exception {
        long starttime=System.currentTimeMillis();
        Thread[] threads=new Thread[100];
        for(int i=0;i<100;i++) {
            threads[i]=new Thread(new TestThreadSingleton());
            threads[i].start();
        }
        for(Thread t:threads)
            t.join();
        Thread.sleep(3000);
        long finishtime=System.currentTimeMillis();
        System.out.println("線程測試完成!");
        System.out.println("測試使用時間爲:"+(finishtime-starttime)+"毫秒");
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章