public class Resource { /** * 直接初始化 * **/ private static Resource resource_static = new Resource(); public static Resource getResourceInstanceStatic(){ return resource_static; } /** * 利用synchronized來實現的線程安全 * **/ private static Resource resource_synchronized = null; public static synchronized Resource getResourceInstanceSynchronized(){ if(null==resource_synchronized){ resource_synchronized = new Resource(); } return resource_synchronized; } /** * 利用JVM自己類加載機制實現的lazy初始化 * **/ private static class ResourceHolder{ public static Resource resource = new Resource(); } public static Resource getResourceInstanceClass(){ return ResourceHolder.resource; } /** * DCL double check locking * 線程不安全 不推薦 * **/ private static Resource resource_dcl = null; public static Resource getResourceInstanceDCL(){ if(null==resource_dcl){ synchronized(Resource.class){ if(null==resource_dcl){ resource_dcl = new Resource(); } } } return resource_dcl; } /** * 線程不安全 不推薦 * **/ private static Resource resource_unsafe = null; public static Resource getResourceInstanceUnSafe(){ if(null==resource_unsafe){ resource_unsafe = new Resource(); } return resource_unsafe; } }