Método Java Object wait(long timeout)
Clase Java Object
El método Object wait(long timeout) hace que el hilo actual entre en estado de espera (bloqueo) hasta que otro hilo llame almétodo notify() de este objetoométodo notifyAll(), o se exceda el tiempo de espera establecido por el parámetro timeout.
Si el parámetro timeout es 0, no se producirá tiempo de espera y se esperará indefinidamente, de manera similar almétodo wait()。
El hilo actual debe ser el propietario del monitor de este objeto; de lo contrario, se producirá unaIllegalMonitorStateExceptionexcepción.
Si el hilo actual se interrumpe por cualquier hilo antes o durante la espera, se lanzará unaInterruptedExceptionexcepción.
Si el parámetro pasado no es válido, se lanzará unaIllegalArgumentExceptionexcepción.
Sintaxis
public final void wait(long timeout)
Parámetros
Valor de retorno
Sin valor de retorno.
Ejemplo
El siguiente ejemplo demuestra el uso del método wait(long timeout):
Ejemplo
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;
public class EjemploTest extends Object {
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(10000);
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 la 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!
Clase Java Object
Otras extensiones