public static Singleton2 getInstance() { lock (obj) { if (singleton == null) { singleton = new Singleton2(); } } return(singleton); }
static void Main(string[] args) { for (int i = 0; i < 10000; i++) { new Thread(() => { Singleton1.getInstance(); }).Start(); new Thread(() => { Singleton2.getInstance(); }).Start(); new Thread(() => { Singleton3.getInstance(); }).Start(); new Thread(() => { Singleton4.getInstance(); }).Start(); } Console.Read(); }
public static Singleton2 GetSingleton() { if (singleton == null) { lock (obj) { if (singleton == null) { singleton = new Singleton2(); } } } return(singleton); }
static void Main(string[] args) { Singleton1 s1 = Singleton1.GetInstance(); s1.Name = "张三"; Singleton2 s2 = Singleton2.GetInStance(); s2.Name = "王五"; Console.WriteLine(s1.Name); Console.WriteLine(s2.Name); Console.ReadKey(); }