Ver Mensaje Individual
  #1 (permalink)  
Antiguo 02/02/2010, 18:46
Avatar de Xerelo
Xerelo
 
Fecha de Ingreso: mayo-2009
Mensajes: 2.175
Antigüedad: 15 años
Puntos: 306
[Solucionado]Threads: ¿Cómo usar wait() y notify()?

Estoy probando la alternancia de hilos, y no soy capaz de devolver a la vida un hilo que está en wait()

Éste es el código que estoy utilizando

Cita:
public class AlterarOrdenHilos {

public static void main(String[] args) throws InterruptedException {

System.out.println("Hilo principal " + Thread.currentThread().toString());

FirstThread f = new FirstThread();
ThirdThread t = new ThirdThread();

f.start();
t.start();
f.join();

System.out.println("Fin del padre2");
try {
//t.interrupt();
//Thread.currentThread().notify();


} catch (Exception e) {}

}

}

class FirstThread extends Thread {
public void run () {
try {
System.out.println(" First thread starts running.");
sleep(10000);
System.out.println(" First thread finishes running.");
} catch (Exception e) {}
}
}


class ThirdThread extends Thread {
public void run () {
try {
System.out.println(" Third thread starts running.");
wait();
System.out.println(" Third thread finishes running.");
} catch (Exception e) {}
}
}
He probado alternativamente las dos opciones en rojo, pero nunca consigo que el ThirdThread muestre el mensaje de salida. Con Thread.currentThread().notify() además obtengo un error IllegalMonitorStateException a pesar de los try/catch, lo mismo que si intento poner al ThirdThreat en wait() desde el man (t.wait() ) en vez de hacerlo desde el run.

¿Cómo puedo reactivarlo? ¿se puede parar desde el main?

Saludos y gracias.

Última edición por Xerelo; 03/02/2010 a las 04:35