Singleton(單例模式)的使用和測試效率
阿新 • • 發佈:2019-02-10
測試時一個一個試
/**
* @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)+"毫秒");
}
}