将synchronized放在 if ( mInstance == null ) 而不直接添加在getInstance方法上,是避免每次都同步该方法而导致的效率低下,当mInstance初始化过后则不需要同步。保证了效率。简单实现如下:
package com.umeng.dp.singleton;
/**
* @Copyright: Umeng.com, Ltd. Copyright 2011-2015, All rights reserved
* @Title: ThreadSingleton.java
* @Package com.umeng.dp.singleton
* @Description: 线程安全的单例模式, synchronized放在mInstance == null条件中保证高并发。
* @author Honghui He
* @version V1.0
*/
public class ThreadSingleton {
private static volatile ThreadSingleton mInstance = null;
/**
* @Title: ThreadSingleton
* @Description: ThreadSingleton Constructor
*/
private ThreadSingleton() {
}
/**
* @Title: getInstance
* @Description: 获取实例
* @return 返回单例
* @throws
*/
public static ThreadSingleton getInstance() {
if (mInstance == null) {
synchronized (ThreadSingleton.class) {
if ( mInstance == null ) {
mInstance = new ThreadSingleton(); }
}
}
return mInstance;
}
}