美文网首页Android面试一问一答
Android面试一问一答:单例

Android面试一问一答:单例

作者: LvStudio | 来源:发表于2019-01-11 08:37 被阅读17次

    手写一个线程安全的单例

    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.)

    相关文章

      网友评论

        本文标题:Android面试一问一答:单例

        本文链接:https://www.haomeiwen.com/subject/bbgzrqtx.html