---
title: "单例模式下的线程安全"
author: "pany"
date: "2012-05-08T15:47:11Z"
tags: []
categories: ["编程语言"]
slug: "untitled"
draft: false
lastmod: "2012-05-08T16:05:48Z"
id: 1517459
url: "https://pany.iteye.com/blog/1517459"
---

```
/*
 * 普通的，线程不安全的单例模式
 */
public class Singleton {

	private static Singleton instance;

	public static Singleton getInstance(){
		if(instance == null){
			return new Singleton();
		}else{
			return instance;
			}	
		}
}
/*
 * 强制实现线程安全的单例模式。
 */
public class Singleton {

    private static Singleton instance;

    public static Singleton getInstance() {

        synchronized (instance) {
            if (instance == null) {

                return new Singleton();

            } else {

                return instance;
            }

        }
    }
}


public class Singleton {
/*
* 静态方法是线程安全的,因为静态方法内声明的变量，每个线程调用时，都会新创建一份，而不会共用一个存储单元
* 静态变量是非线程安全的,由于是在类加载时占用一个存储区，每个线程都是共用这个存储区的，所以如果在静态方法里使用了静态变量，这就会有线程安全问题！
*/
	 static class SingletonHolder {     
		    
	        static Singleton instance = new Singleton();     
	    
	    }     
	    
	    public static Singleton getInstance() {     
	    
	        return SingletonHolder.instance;     
	    
	    }  
}
```