Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.util.Scanner;
- class TareaS implements Runnable
- {
- private String ms;
- Thread tr;
- public TareaS (String m)
- {
- ms = m;
- tr = new Thread(this, ms);
- System.out.println ("Creacción hilo:" + tr);
- tr.start ( ); // ejecutandose
- }
- public void run ( )
- {
- try {
- for (int i = 6; i > 0; i-= 2)
- {
- System.out.println ("Hilo: " + tr + " i = " + i);
- tr.sleep (1000); // Hilo "durmiendo", queda bloqueado
- }
- }
- catch (InterruptedException e)
- {
- e.printStackTrace ( );
- }
- System.out.println ("Finaliza Hilo " + ms);
- }
- }
- public class TresHilosJoin
- {
- public static void main (String [ ] a)
- {
- Scanner entrada = new Scanner (System.in);
- int opcion;
- do {
- System.out.println ("1. Ejecutar con join ( )");
- System.out.println ("2. Ejecutar sin join ( )");
- opcion = entrada.nextInt ( );
- } while (opcion != 1 && opcion !=2);
- // Se crean tres hilos
- TareaS t1, t2, t3;
- t1 = new TareaS ("Primero");
- t2 = new TareaS ("Segundo");
- t3 = new TareaS ("Tercero");
- System.out.println ("Hilo ejecutandose: " +
- Thread.currentThread ( ) );
- if (opcion == 1)
- {
- System.out.println ("Cada hilo llamada a join( )");
- try {
- t1.tr.join ( ); //Hilo actual "bloqueado" hasta finalizar t1
- t2.tr.join ( );
- t3.tr.join ( );
- }
- catch (InterruptedException e)
- {
- e.printStackTrace ( );
- }
- }
- else
- System.out.println ("No hay llamada a join ( )");
- //
- System.out.println ("Finaliza hilo main ( )" );
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment