using System;
using System.Threading;
namespace PangPingPongPung
{
public class Contador
{
const int NUM_HILOS=4;
private int Turno;
private string[] Mensajes={"pang", "ping", "pong", "pung"};
public Contador(int Turno)
{
this.Turno=Turno;
}
public void Incrementar()
{
Turno++;
}
public string ValorActual()
{
return (Turno%NUM_HILOS).ToString();
}
public string MensajeActual()
{
return Mensajes[Turno%NUM_HILOS];
}
}
class Program
{
private Contador c;
const int NUM_HILOS=4;
public Program(int turnoInicial)
{
Thread [] vThreads=new Thread[4];
c=new Contador(turnoInicial);
for (int I=0; I<NUM_HILOS; I++) {
vThreads[I]=new Thread(new ThreadStart(pangpingpongpung));
vThreads[I].Name=I.ToString();
vThreads[I].Start();
if (I<NUM_HILOS-1)
vThreads[I].Join(20);
else
vThreads[I].Join(10000);
}
for (int I=0; I<NUM_HILOS; I++)
vThreads[I].Abort();
Console.Write("Press any key to continue . . . ");
Console.ReadKey(true);
}
public static void Main(string[] args)
{
Program p=new Program(0);
}
public void pangpingpongpung()
{
while (true) {
Monitor.Enter(c);
try{
if (Thread.CurrentThread.Name==c.ValorActual()) {
Console.WriteLine(c.MensajeActual());
c.Incrementar();
int esperaAleatoria=new Random(
DateTime.Now.Millisecond).Next()%500;
Thread.Sleep(esperaAleatoria);
}
}
finally {
Monitor.Exit(c);
}
}
}
}
}
martes, 29 de marzo de 2011
Solución al ejercicio propuesto de Threads "pang-ping-pong-pung"
Suscribirse a:
Enviar comentarios (Atom)
No hay comentarios:
Publicar un comentario