Una forma sencilla y rápida de aprender JAVA, observando y deduciendo cómo se comporta el lenguaje a través de ejemplos prácticos.

Archivo del blog

martes, 3 de abril de 2012

Hilos: Creando segundo hilo usando Runnable.

Codigo:

//Crear un hilo con interface Runnable
package hilos1;

class Hilo2 implements Runnable {

Thread hilo2;
Hilo2() {
hilo2 = new Thread(this, "segundo");
System.out.println("Inicio segundo hilo");
hilo2.start();//Inicia segundo hilo
}

public void run() {
try {
for(int i=0; i<5; i++){
System.out.println((Thread.currentThread()).getName()+" hilo aqui...");
Thread.sleep(1000);
}
} catch (InterruptedException ex) {}
System.out.println("Final del segundo hilo");
}
}

class Hilos1 {
public static void main(String[] args) { //Hilo principal (main)
new Hilo2(); //Segundo hilo (segundo)
try {
for(int i=0; i<5; i++){
System.out.println((Thread.currentThread()).getName()+" hilo aqui...");
Thread.sleep(1000);
}
} catch (InterruptedException ex) {}
}
}


Resultado:

run:
Inicio segundo hilo
main hilo aqui...
segundo hilo aqui...
segundo hilo aqui...
main hilo aqui...
segundo hilo aqui...
main hilo aqui...
main hilo aqui...
segundo hilo aqui...
main hilo aqui...
segundo hilo aqui...
Final del segundo hilo
BUILD SUCCESSFUL (total time: 5 seconds)
·
Con la tecnología de Blogger.