C# 单例模式–懒汉
代码:SingletonLazy.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace SingletonLazy
{
public class Singleton
{
#region 单例模式--懒汉模式
private static Singleton instance { get; set; }
private static readonly object lockRoot = new object();
private Singleton()
{
Count = 0;
Console.WriteLine("单例---结构体");
}
public static Singleton getInstance()
{
if (instance == null)
{
Console.WriteLine("单例---实例化 验证一");
lock (lockRoot){
Console.WriteLine("单例---实例化 验证二");
if (instance == null)
instance = new Singleton();
}
}
return instance;
}
#endregion
#region 累加测试
private int Count { get; set; }
public void AddCount()
{
lock(Singleton.lockRoot)
{
Console.WriteLine("累加---" + Count.ToString("D5"));
Count++;
Thread.Sleep(10);
}
}
#endregion
}
}
代码:program.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace SingletonLazy
{
class Program
{
static void Main(string[] args)
{
new Program().loopCal();
Console.Read();
}
private void loopCal()
{
while (true)
{
Thread t1 = new Thread(() =>
{
Singleton.getInstance().AddCount();
});
Thread t2 = new Thread(() =>
{
Singleton.getInstance().AddCount();
});
t1.Start();
t2.Start();
t1.Join();
t2.Join();
}
}
}
}