单例模式Singleton Pattern 在多线程下的问题

来源:互联网 发布:域名怎么跳转代码 编辑:程序博客网 时间:2024/05/23 13:48

单例模式很简单,一般简单写成为如下:

public class Singleton {private static Singleton singleton=new Singleton(); //类Singleton在加载进JVM时,就首先定义好了类成员变量singleton private Singleton() {}public static Singleton getInstance() {return singleton;}

这种单例模式的写法,在多线程条件下不会出现问题。因为当类Singleton被加载进JVM时,就首先定义好了类成员变量singleton ,也就是new好了唯一的一个实例对象。

无论多少个线程进入getInstance(),都return唯一的实例对象。ok,这种写法无懈可击。


单例模式还有种写法:

public class Singleton {private static Singleton singleton;private Singleton() {}public static Singleton getInstance() {              if(singleton==null)     //statement1              {                   singleton=new Singleyon();  //statement2              }              return singleton;}
这种单例模式的写法在单线程执行时,没问题只会产生一个实例对象。但在多线程情况下,可能会new出不只一个实例对象,下面模拟一种出问题的可能:

两个线程th1和th2,当th1执行完statememt1时,还未执行statement2时,CPU这时切换到th2执行,th2执行statement1,判断singleton仍未null,接着执行statement2,new出了新的实例对象instance1 。接着CPU切换回th1,th1继续执行statement2,又new出了一个实例对象instance2。 显然,instance1和instance2是不同的实例对象,与单例模式只产生一个实例对象的本意相悖。

模拟代码如下:

package com.wrongWithThread.Singleton;public class Singleton {private static Singleton singleton;private Singleton() {}public static Singleton getInstance() {if (singleton == null) {           //statement1try {Thread.sleep((long) (Math.random() * 4000));} catch (InterruptedException e) {e.printStackTrace();}singleton = new Singleton();         //statement2}return singleton;}public static void main(String[] args) {myThread th1 = new myThread();myThread th2 = new myThread();th1.start();th2.start();}}class myThread extends Thread {@Overridepublic void run() {System.out.println(Singleton.getInstance()); //打印实例对象的toString();}}
显然,打印出两个实例对象是不同的:

com.wrongWithThread.Singleton.Singleton@e6f7d2
com.wrongWithThread.Singleton.Singleton@19836ed


解决方法:

public synchronized static Singleton getInstance() 
方法进行synchronize 使得当线程th1访问该static方法时,拿走Singleton类的Class对象锁(注意一个类只有一个锁,这里是对整个类加锁,而不是对象锁)  ,使得th2不能访问getInstance()方法,直到th1释放了类的锁。这时singleton已经不为null了。

改进多线程下的单例模式如下:

package com.wrongWithThread.Singleton;public class Singleton {private static Singleton singleton;private Singleton() {}public synchronized static Singleton getInstance() {  //对该静态方法synchronized if (singleton == null) {try {Thread.sleep((long) (Math.random() * 4000));} catch (InterruptedException e) {e.printStackTrace();}singleton = new Singleton();}return singleton;}public static void main(String[] args) {myThread th1 = new myThread();myThread th2 = new myThread();th1.start();th2.start();}}class myThread extends Thread {@Overridepublic void run() {System.out.println(Singleton.getInstance().toString());}}

ok,这时打印的是同一个实例对象:

com.wrongWithThread.Singleton.Singleton@120bf2c
com.wrongWithThread.Singleton.Singleton@120bf2c

0 0
原创粉丝点击