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

©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • rljs by sennchi Timeline of History Part One The Cognitiv...
    sennchi阅读 12,183评论 0 10
  • 开发过程中会遇到蓝牙开发,目前蓝牙分两种,一种3.0经典蓝牙,可以大数据传输的,可以传输图片,歌曲和视频的;一种是...
    枫雪狼情阅读 11,222评论 0 50
  • 涵箫琪阅读 1,454评论 2 7
  • 文/路人锋 我和一对影子站在路灯下丈量你我之间夜色的距离偶过的汽车也懂我的情意哼着滴曲演绎跳跃的旋律 崭新的桥,红...
    路人锋阅读 5,706评论 24 33

友情链接更多精彩内容