Skip to content

Instantly share code, notes, and snippets.

@Fhernd
Created July 9, 2014 23:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Fhernd/8fc616960b8fc5a1f20d to your computer and use it in GitHub Desktop.
Save Fhernd/8fc616960b8fc5a1f20d to your computer and use it in GitHub Desktop.
Uso de los métodos Pulse y Wait de la clase Monitor.
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 ();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment