---
title: "java完整的单例代码(切记)"
author: "keren"
date: "2017-05-11T09:56:37Z"
tags: []
categories: ["编程语言"]
slug: "java"
draft: false
lastmod: "2017-05-11T10:06:38Z"
id: 2373726
url: "https://keren.iteye.com/blog/2373726"
---

```java

    // 这里要加 volatile 防止指令重排
    private static volatile A instance = null;

    private A() {
        
    }

    public static AgetInstance() {
        if (instance == null) {// 只有为null，才进入同步锁，减少多线程等待
            synchronized (A.class) { // 这里要加 锁，防止多线程
                if (instance == null) {// 这里要加判断，防止出现多个实例
                    instance = new A();
                }
            }
        }
        return instance;
    }

```