4
這個例子有什麼問題,它在Monitor.PulaseAll(yyy)上拋出錯誤「對象同步方法是從一個非同步的代碼塊中調用的?這裏Monitor.PulaseAll拋出錯誤
class Program
{
static object yyy = 1;
public static void test(int x)
{
while (true)
{
lock (yyy)
{
Console.WriteLine("T" + x.ToString());
while (x != (int)yyy)
{
Monitor.Wait(yyy);
continue;
}
Console.Write(new string(x.ToString()[0], 20));
yyy = 1 + (int)yyy;
yyy = ((int)yyy == 4) ? 1 : yyy;
Console.WriteLine("------------------------1--");
Monitor.PulseAll(yyy);
Console.WriteLine("------------------------2--");
}
}
}
public static void Main()
{
Thread t1 = new Thread(new ThreadStart(() => { test(3);}));
Thread t2 = new Thread(new ThreadStart(() => { test(2);}));
Thread t3 = new Thread(new ThreadStart(() => { test(1);}));
t1.Start();
t2.Start();
t3.Start();
while (true)
Thread.Sleep(500);
}
}