class Program12
{
static object obj = new object();
static int lastNum = 4;
static void WriteNum(object i)
{
//lock (obj)
//{
//Console.Write(i); //输出:1234 不加lock是无序的输出 2134 1324 等
//}
//循环写入10次 1234
for (int k = 0; k < 10; k++)
{
lock (obj)
{
if ((int)i == lastNum + 1|| (int)i == lastNum - 3)
{
if ((int)i==4)
{
Console.WriteLine(i);
}
else
{
Console.Write(i);
}
lastNum = (int)i;
Monitor.PulseAll(obj);
}
else
{
k--;
Monitor.Wait(obj);
}
}
}
}
static void Main(string[] args)
{
Thread t1 = new Thread(WriteNum);
Thread t2 = new Thread(WriteNum);
Thread t3 = new Thread(WriteNum);
Thread t4 = new Thread(WriteNum);
t1.Start(1);
t2.Start(2);
t3.Start(3);
t4.Start(4);
Console.ReadLine();
}
}