摘要:SingleTon模式的Thread_Safe
以下是SingleTon模式下,針對Multi-Thread做資料鎖定的做法:
class Sync
{
public void Do(object state)
{
lock (this)
{
int j = (int)state;
for (int i = 1; i <= 10; i++)
Console.WriteLine("{0} - {1}", j, i);
}
}
}
{
public void Do(object state)
{
lock (this)
{
int j = (int)state;
for (int i = 1; i <= 10; i++)
Console.WriteLine("{0} - {1}", j, i);
}
}
}
下面則是另一種做法(看起來跟Java比較接近):
using System;
using System.Runtime.CompilerServices;
using System.Threading;
class Program
{
public static void Main()
{
Sync s = new Sync();
for (int i = 1; i <= 2; i++)
new Thread(new ParameterizedThreadStart(s.Do)).Start(i);
Console.ReadLine();
}
}
class Sync
{
[MethodImpl(MethodImplOptions.Synchronized)]
public void Do(object state)
{
int j = (int)state;
for (int i = 1; i <= 10; i++)
Console.WriteLine("{0} - {1}", j, i);
}
}
using System.Runtime.CompilerServices;
using System.Threading;
class Program
{
public static void Main()
{
Sync s = new Sync();
for (int i = 1; i <= 2; i++)
new Thread(new ParameterizedThreadStart(s.Do)).Start(i);
Console.ReadLine();
}
}
class Sync
{
[MethodImpl(MethodImplOptions.Synchronized)]
public void Do(object state)
{
int j = (int)state;
for (int i = 1; i <= 10; i++)
Console.WriteLine("{0} - {1}", j, i);
}
}