Método Java Object wait()
El método wait() de Object hace que el hilo actual entre en estado de espera. Hasta que otro hilo llame a este objeto:método notify()ométodo notifyAll()。
El hilo actual debe ser el propietario del monitor de este objeto; de lo contrario, se producirá unaIllegalMonitorStateExceptionexcepción.
Si el hilo actual es interrumpido por algún hilo antes o durante la espera, se lanzará unaInterruptedExceptionexcepción.
Sintaxis
public final void wait()
Parámetros
Ninguno 。
Valor de retorno
No hay valor de retorno.
Ejemplo
El siguiente ejemplo demuestra el uso del método wait():
Ejemplo
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;
public class EjemploTest extends Object {
private List synchedList;
public EjemploTest() {
//Crear una lista sincronizada
synchedList = Collections.synchronizedList(new LinkedList());
}
//Eliminar elementos de la lista
public String removeElement() throws InterruptedException {
synchronized (synchedList) {
//Si la lista está vacía, esperar
while (synchedList.isEmpty()) {
System.out.println("List is empty...");
synchedList.wait();
System.out.println("Waiting...");
}
String element = (String) synchedList.remove(0);
return element;
}
}
//Agregar elementos a la lista
public void addElement(String element) {
System.out.println("Opening...");
synchronized (synchedList) {
//Agregar un elemento y notificar que el elemento ya existe
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() {
//Realizar la operación de agregar elemento y comenzar el bucle
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 ejecución del programa anterior es:
List is empty... List is empty... Opening... New Element:'Hello!' notifyAll called! Closing... Waiting... Waiting... List is empty... Hello! Interrupted Exception!
Otras extensiones
Clase Java Object