Singleton(单例模式)的使用和测试效率

来源:互联网 发布:淘宝宝妈法兰西 编辑:程序博客网 时间:2024/06/05 05:05

测试时一个一个试

/** * @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)+"毫秒");    }}
原创粉丝点击