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)+"毫秒");
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值