在多线程程序中,必须要考虑进程间共享和互斥的问题。 如果恰巧有两个线程访问Singleton类,并做修改的话,会导致出现bug。
解决的方法就是给对象加锁:
Java:
//
: Configuration.java
/** */ /**
* Singleton of Design Patterns
* @author http://blog.csdn.net/nyzhl/
*/
public class Configuration ... {
private static Configuration _instance = null;
//私有构造函数 不能在类外部生成对象
private Configuration() ...{}
public static synchronized Configuration getInstance() ...{
if(_instance == null)
_instance = new Configuration();
return _instance;
}
/**//*
methods ...
*/
}
// /:~
/** */ /**
* Singleton of Design Patterns
* @author http://blog.csdn.net/nyzhl/
*/
public class Configuration ... {
private static Configuration _instance = null;
//私有构造函数 不能在类外部生成对象
private Configuration() ...{}
public static synchronized Configuration getInstance() ...{
if(_instance == null)
_instance = new Configuration();
return _instance;
}
/**//*
methods ...
*/
}
// /:~
C#:
using
System;
public sealed class Singleton
... {
private static volatile Singleton instance;
private static object syncRoot = new Object();
private Singleton() ...{}
public static Singleton Instance
...{
get
...{
if (instance == null)
...{
lock (syncRoot)
...{
if (instance == null)
instance = new Singleton();
}
}
return instance;
}
}
}
public sealed class Singleton
... {
private static volatile Singleton instance;
private static object syncRoot = new Object();
private Singleton() ...{}
public static Singleton Instance
...{
get
...{
if (instance == null)
...{
lock (syncRoot)
...{
if (instance == null)
instance = new Singleton();
}
}
return instance;
}
}
}