Android面试一问一答:单例

手写一个线程安全的单例

public class Singleton{
    private static volatile Singleton mInstance;
    private Singleton() {
    }
    public static Singleton getInstance() {
        if(mInstance == null) {
            synchronized(Singleton.class) {
                if(mInstance == null) {
                    mInstance = new Singleton;
                }
            }
        }
        return mInstance;
    }
}

volatile关键字有什么作用

  • volatile关键字保证了对mInstance这个引用操作时对其他线程的可见性。

(参考一: In Java, each thread has a separate memory space known as working memory; this holds the values of different variables used for performing operations. After performing an operation, thread copies the updated value of the variable to the main memory, and from there other threads can read the latest value.
Simply put, the volatile keyword marks a variable to always go to main memory, for both reads and writes, in the case of multiple threads accessing it.)

(参考二:The Java volatile keyword is used to mark a Java variable as “being stored in main memory”. More precisely that means, that every read of a volatile variable will be read from the computer’s main memory, and not from the CPU cache, and that every write to a volatile variable will be written to main memory, and not just to the CPU cache.

Actually, since Java 5 the volatile keyword guarantees more than just that volatile variables are written to and read from main memory.)

    原文作者:LvStudio
    原文地址: https://www.jianshu.com/p/127073a0bf8a
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞