单例在线程并发时的创建

1.使用synchronized:
        public static SpeechApi getInstance() {
if (mInstance == null) {
synchronized (SpeechApi.class) {
if (mInstance == null) {
mInstance = new SpeechApi();
}
}
}
return mInstance;
}
2.使用final类型定义:
public class SingleInstance {
private static final SingleInstance instance = new SingleInstance();
private SingleInstance(){

}
public static SingleInstance getInstance(){
return instance;
}
}

猜你喜欢

转载自wudukongjian007-163-com.iteye.com/blog/1654621