Advertisement
Fhernd

UsoThreadJoinInt32.cs

Jun 26th, 2014
1,743
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.93 KB | None | 0 0
  1. using System;
  2. using System.Threading;
  3.  
  4. namespace Recetas.Multithreading.Cap01
  5. {
  6.     internal sealed class UsoThreadJoinInt32
  7.     {
  8.         // Declaración de threads:
  9.         private static Thread threadMain, thread1, thread2;    
  10.    
  11.         public static void Main()
  12.         {
  13.             threadMain = Thread.CurrentThread;
  14.            
  15.             thread1 = new Thread (ProcesoThread);
  16.             // El nombre facilita su identificación:
  17.             thread1.Name = "Thread1";
  18.             thread1.Start();
  19.            
  20.             // Crea una instancia de Thread:
  21.             thread2 = new Thread (ProcesoThread);
  22.             // El nombre facilita su identificación:
  23.             thread2.Name = "Thread2";
  24.             thread2.Start();
  25.         }
  26.        
  27.         // Este método es el encargado de llevar a cabo
  28.         // la tarea de ejecución de threads:
  29.         private static void ProcesoThread()
  30.         {
  31.             Console.WriteLine ("\nThread en curso: {0}", Thread.CurrentThread.Name);
  32.            
  33.             if (Thread.CurrentThread.Name.Equals ("Thread1") &&
  34.                 thread2.ThreadState != ThreadState.Unstarted)
  35.             {
  36.                 // Espera a por 2 segundos a que `thread2` termine:
  37.                 if (thread2.Join (2000))
  38.                 {
  39.                     Console.WriteLine ("`thread2` ha terminado su ejecución.");
  40.                 }
  41.                 else
  42.                 {
  43.                     Console.WriteLine ("El tiempo de espera ha transcurrido el `thread1` continuará su ejecución.");
  44.                 }
  45.             }
  46.            
  47.             // Pausa el thread por 4 segundos:
  48.             Thread.Sleep (4000);
  49.            
  50.             Console.WriteLine ("\nThread en curso: {0}", Thread.CurrentThread.Name);
  51.             Console.WriteLine ("`thread1`: {0}", thread1.ThreadState);
  52.             Console.WriteLine ("`thread2`: {0}\n", thread2.ThreadState);
  53.         }
  54.     }
  55. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement