using System; using System.Threading; namespace Recetas.CSharp.Cap04.R0407 { public class TicTac { public void Tic (bool enEjecucion) { lock (this) { if (!enEjecucion) { // Notifica a los threads en espera: Monitor.Pulse (this); return; } Thread.Sleep (1000); Console.Write ("Tic "); // Permite el paso de la ejecución del método Tac Monitor.Pulse (this); // ...y espera a que el método Tac termine: Monitor.Wait (this); } } public void Tac (bool enEjecucion) { lock (this) { if (!enEjecucion) { // Notifica a los threads en espera: Monitor.Pulse (this); return; } Thread.Sleep (1000); Console.WriteLine ("Tac"); // Permite el paso de la ejecución del método Tic Monitor.Pulse (this); // ...y espera a que el método Tic termine: Monitor.Wait (this); } } } public sealed class TicTacPulse { public static TicTac ticTac; public static void IniciarReloj() { if (Thread.CurrentThread.Name.Equals ("Tic")) { // Repite el sonido tic 5 veces: for (int i = 1; i <= 5; ++i) { ticTac.Tic(true); } // Detiene el sonido tic: ticTac.Tic (false); } else { // Repite el sonido tac 5 veces: for (int i = 1; i <= 5; ++i) { ticTac.Tac (true); } // Detiene el sonido tac: ticTac.Tac (false); } } public static void Main() { ticTac = new TicTac(); // Crea dos threads: Thread t1 = new Thread (IniciarReloj); t1.Name = "Tic"; Thread t2 = new Thread (IniciarReloj); t2.Name = "Tac"; t1.Start (); t2.Start (); t1.Join(); t2.Join(); Console.WriteLine ("\nEl reloj se ha detenido. Presione Enter."); Console.ReadLine (); } } }