Data hosted with ♥ by Pastebin.com - Download Raw - See Original
  1. using System;
  2. using System.Threading;
  3.  
  4. namespace Recetas.CSharp.Cap04.R0407
  5. {
  6.     public class BlogxCSw
  7.     {
  8.         // Representa el número de threads máximos
  9.         // soportados por el servidor:
  10.         private const int threads = 3;
  11.        
  12.         // Representa la cantidad de usuarios que
  13.         // se van a conectar al blog:
  14.         private const int usuarios = 20;
  15.        
  16.         // Representa el locker que se encarga de
  17.         // controlar el acceso al blog:
  18.         private static Object locker = new Object();
  19.        
  20.         // Permite a un usuario ingresar al usuario:
  21.         public static void IngresarAlBlog()
  22.         {
  23.             while (true)
  24.             {
  25.                 lock (locker)
  26.                 {
  27.                     Monitor.Wait (locker);
  28.                 }
  29.                
  30.                 Console.WriteLine ("{0} accedió al Blog xCSw",
  31.                     Thread.CurrentThread.Name
  32.                 );
  33.                
  34.                 Thread.Sleep (150);
  35.             }
  36.         }
  37.        
  38.         public static void Main()
  39.         {
  40.             // Creación del pool de threads:
  41.             Thread[] pool = new Thread[threads];
  42.            
  43.             // Creación de cada uno de los threads:
  44.             for (int i = 0; i < threads; ++i)
  45.             {
  46.                 pool[i] = new Thread (new ThreadStart (IngresarAlBlog));
  47.                 pool[i].Name = String.Format ("Usuario {0}", (i + 1).ToString() );
  48.                 pool[i].IsBackground = true;
  49.                 pool[i].Start();
  50.             }
  51.            
  52.             // Atienda las visitas al blog:
  53.             for (int i = 1; i <= usuarios; ++i)
  54.             {
  55.                 Thread.Sleep (1000);
  56.                
  57.                 lock (locker)
  58.                 {
  59.                     Monitor.Pulse (locker);
  60.                 }
  61.             }
  62.            
  63.             Console.WriteLine ();
  64.         }
  65.     }
  66. }