Método notify() de Java Object
Clase Object de Java
El método notify() de Object se utiliza para despertar un hilo que está esperando en el monitor de este objeto.
Si todos los hilos están esperando en este objeto, solo se seleccionará un hilo; la selección es arbitraria y ocurre cuando la implementación toma la decisión.
Un hilo puede esperar en el monitor de un objeto llamando al método wait().
El método notify() solo puede ser llamado por el hilo que sea el propietario del monitor de este objeto.
Para que un hilo se convierta en el propietario del monitor de un objeto, puede usar los siguientes 3 métodos:
- Ejecutar un método de instancia sincronizado del objeto
- Usar el bloqueo integrado de synchronized
- Para objetos de tipo Class, ejecutar métodos estáticos sincronizados
Solo un hilo puede poseer el monitor del objeto a la vez.
Si el hilo actual no es el propietario del monitor de este objeto, se lanzaráIllegalMonitorStateExceptionuna excepción.
Sintaxis
public final void notify()
Parámetros
Valor de retorno
No tiene valor de retorno.
Ejemplo
El siguiente ejemplo demuestra el uso del método notify():
Ejemplo
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;
public class EjemploTest {
private List synchedList;
public EjemploTest() {
synchedList = Collections.synchronizedList(new LinkedList());
}
public String removeElement() throws InterruptedException {
synchronized (synchedList) {
while (synchedList.isEmpty()) {
System.out.println("List is empty...");
synchedList.wait();
System.out.println("Waiting...");
}
String element = (String) synchedList.remove(0);
return element;
}
}
public void addElement(String element) {
System.out.println("Opening...");
synchronized (synchedList) {
synchedList.add(element);
System.out.println("New Element:'" + element + "'");
synchedList.notifyAll();
System.out.println("notifyAll called!");
}
System.out.println("Closing...");
}
public static void main(String[] args) {
final EjemploTest demo = new EjemploTest();
Runnable runA = new Runnable() {
public void run() {
try {
String item = demo.removeElement();
System.out.println("" + item);
} catch (InterruptedException ix) {
System.out.println("Interrupted Exception!");
} catch (Exception x) {
System.out.println("Exception thrown.");
}
}
};
Runnable runB = new Runnable() {
public void run() {
demo.addElement("Hello!");
}
};
try {
Thread threadA1 = new Thread(runA, "Google");
threadA1.start();
Thread.sleep(500);
Thread threadA2 = new Thread(runA, "Ejemplo");
threadA2.start();
Thread.sleep(500);
Thread threadB = new Thread(runB, "Taobao");
threadB.start();
Thread.sleep(1000);
threadA1.interrupt();
threadA2.interrupt();
} catch (InterruptedException x) {
}
}
}
El resultado de ejecutar el programa anterior es:
List is empty...
List is empty...
Opening...
New Element:'Hello!'
notifyAll called!
Closing...
Waiting...
Waiting...
List is empty...
Hello!
Interrupted Exception!
Clase Object de Java
Otras extensiones