fork download
  1. using System;
  2. using System.Threading;
  3.  
  4. namespace Recetas.Multithreading.Cap01.R0107
  5. {
  6. public sealed class IteracionesThreads
  7. {
  8. public static void Main()
  9. {
  10. Console.Title = "Iteraciones Threads";
  11. Console.WriteLine ();
  12.  
  13. // Creación de dos threads:
  14. Thread t1 = new Thread (
  15. new ParameterizedThreadStart (ContadorNumeros)
  16. );
  17. t1.Name = "ForegroundThread";
  18. Thread t2 = new Thread (
  19. new ParameterizedThreadStart (ContadorNumeros)
  20. );
  21. t2.Name = "BackgroundThread";
  22.  
  23. // Hace que el thread `t2` sea de segundo plano:
  24. t2.IsBackground = true;
  25.  
  26. // Número de iteraciones para cada thread:
  27. t1.Start(13);
  28. t2.Start(17);
  29. }
  30.  
  31. public static void ContadorNumeros(object iteraciones)
  32. {
  33. int it = (int) iteraciones;
  34.  
  35. for (int i = 1; i <= it; ++i)
  36. {
  37. // Suspende el thread 0.5 segundos:
  38. Thread.Sleep (TimeSpan.FromSeconds (0.5));
  39. Console.WriteLine ("El thread `{0}` imprime {1}",
  40. Thread.CurrentThread.Name,
  41. i.ToString()
  42. );
  43. }
  44. }
  45. }
  46. }
Success #stdin #stdout 0.03s 35968KB
stdin
Standard input is empty
stdout
El thread `ForegroundThread` imprime 1
El thread `BackgroundThread` imprime 1
El thread `BackgroundThread` imprime 2
El thread `ForegroundThread` imprime 2
El thread `BackgroundThread` imprime 3
El thread `ForegroundThread` imprime 3
El thread `BackgroundThread` imprime 4
El thread `ForegroundThread` imprime 4
El thread `BackgroundThread` imprime 5
El thread `ForegroundThread` imprime 5
El thread `BackgroundThread` imprime 6
El thread `ForegroundThread` imprime 6
El thread `BackgroundThread` imprime 7
El thread `ForegroundThread` imprime 7
El thread `BackgroundThread` imprime 8
El thread `ForegroundThread` imprime 8
El thread `BackgroundThread` imprime 9
El thread `ForegroundThread` imprime 9
El thread `ForegroundThread` imprime 10
El thread `BackgroundThread` imprime 10
El thread `ForegroundThread` imprime 11
El thread `BackgroundThread` imprime 11
El thread `ForegroundThread` imprime 12
El thread `BackgroundThread` imprime 12
El thread `ForegroundThread` imprime 13