Please disable your AD blocker to continue using this site. Ads help us keep the content free! please press keyboard F5 to refresh page after disabled AD blocker
classProgram { staticvoidMain(string[] args) { Alternate c = new Alternate(); var t1 = new Thread(c.CallA); var t2 = new Thread(c.CallB); var t3 = new Thread(c.CallC);
t1.Start(); t2.Start(); t3.Start();
t1.Join(); t2.Join(); t3.Join();
Console.ReadKey(); } } publicclassAlternate { publicvoidCallA() { for (int i = 0; i < 20; i++) { Console.WriteLine("A"); } }
publicvoidCallB() { for (int i = 0; i < 20; i++) { Console.WriteLine("B"); }
} publicvoidCallC() { for (int i = 0; i < 20; i++) { Console.WriteLine("C"); } } }
AutoResetEvent notifyA = new AutoResetEvent(false); AutoResetEvent notifyB = new AutoResetEvent(false); AutoResetEvent notifyC = new AutoResetEvent(false); privatevolatileint index = 1; publicvoidCallA() { for (int i = 0; i < 20; i++) { if (index != 1) notifyA.WaitOne();
Console.WriteLine("A"); index = 2; notifyB.Set(); }
}
publicvoidCallB() { for (int i = 0; i < 20; i++) { if (index != 2) notifyB.WaitOne();
Console.WriteLine("B"); index = 3; notifyC.Set(); }
} publicvoidCallC() { for (int i = 0; i < 20; i++) { if (index != 3) notifyC.WaitOne();
Console.WriteLine("C"); Console.WriteLine("------------------------------"); index = 1; notifyA.Set(); } } }