Metziop

Untitled

May 13th, 2021
623
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. import java.util.Scanner;
  2. class TareaS implements Runnable
  3. {
  4. private String ms;
  5. Thread tr;
  6. public TareaS (String m)
  7. {
  8. ms = m;
  9. tr = new Thread(this, ms);
  10. System.out.println ("Creacción hilo:" + tr);
  11. tr.start ( ); // ejecutandose
  12. }
  13. public void run ( )
  14. {
  15. try {
  16. for (int i = 6; i > 0; i-= 2)
  17. {
  18. System.out.println ("Hilo: " + tr + " i = " + i);
  19. tr.sleep (1000); // Hilo "durmiendo", queda bloqueado
  20. }
  21. }
  22. catch (InterruptedException e)
  23. {
  24. e.printStackTrace ( );
  25. }
  26. System.out.println ("Finaliza Hilo " + ms);
  27. }
  28. }
  29. public class TresHilosJoin
  30. {
  31. public static void main (String [ ] a)
  32. {
  33. Scanner entrada = new Scanner (System.in);
  34. int opcion;
  35. do {
  36. System.out.println ("1. Ejecutar con join ( )");
  37. System.out.println ("2. Ejecutar sin join ( )");
  38. opcion = entrada.nextInt ( );
  39. } while (opcion != 1 && opcion !=2);
  40. // Se crean tres hilos
  41. TareaS t1, t2, t3;
  42. t1 = new TareaS ("Primero");
  43. t2 = new TareaS ("Segundo");
  44. t3 = new TareaS ("Tercero");
  45. System.out.println ("Hilo ejecutandose: " +
  46. Thread.currentThread ( ) );
  47. if (opcion == 1)
  48. {
  49.  
  50. System.out.println ("Cada hilo llamada a join( )");
  51. try {
  52. t1.tr.join ( ); //Hilo actual "bloqueado" hasta finalizar t1
  53. t2.tr.join ( );
  54. t3.tr.join ( );
  55. }
  56. catch (InterruptedException e)
  57. {
  58. e.printStackTrace ( );
  59. }
  60. }
  61. else
  62. System.out.println ("No hay llamada a join ( )");
  63. //
  64. System.out.println ("Finaliza hilo main ( )" );
  65. }
  66. }
RAW Paste Data