class Program
{
static void Main(string[] args)
{
Thread t1 = new Thread(new ThreadStart(ThreadProc1));
Thread t2 = new Thread(new ThreadStart(ThreadProc2));
t1.Start();
t2.Start();
t1.Join();
t2.Join();
Console.ReadLine();
}
public static void ThreadProc1()
{
for (int i = 0; i < 10; i++)
{
Singleton.Instance.IntCnt += 1;
Console.WriteLine("Proc1:" + Singleton.Instance.IntCnt);
}
}
public static void ThreadProc2()
{
for (int i = 0; i < 10; i++)
{
Singleton.Instance.IntCnt += 1;
Console.WriteLine("Proc2:" + Singleton.Instance.IntCnt);
}
}
}
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;
}
}
private int intCnt;
public int IntCnt
{
get { return intCnt; }
set { intCnt = value; }
}
}