对共享对象(N个线程可能会同时操作的对象)同步
class Program
{
static string[] temp = new string[3] { "0000", "-", "0000" };
static void Main(string[] args)
{
Thread t1 = new Thread(Program.changeArray);
t1.Start("1");
Thread.Sleep(5);
Thread t2 = new Thread(Program.changeArray);
t2.Start("2");
Console.Read();
}
public static void changeArray(object str)
{
//Console.Write("线程"+str.ToString()+"启动\r\n");
lock (temp.SyncRoot)
{
Console.Write("线程" + str.ToString() + "lock\r\n");
//Thread.Sleep(5000);
temp[0] = str.ToString();
for (int i = 0; i < temp.Length; i++)
{
Console.Write(temp[i]);
}
Console.Write("\r\n");
}
}
public static void changeArray2(object str)
{
Console.Write("线程2启动\r\n");
lock (temp.SyncRoot)
{
temp[0] = str.ToString();
for (int i = 0; i < temp.Length; i++)
{
Console.Write(temp[i]);
}
Console.Write("\r\n");
}
}