Java-Object-wait()-Methode

Java String类Java Object-Klasse


Die wait()-Methode von Object versetzt den aktuellen Thread in den Wartezustand. Bis ein anderer Thread dienotify()-MethodeodernotifyAll()-Methode dieses Objekts aufruft。

Der aktuelle Thread muss der Monitor-Inhaber dieses Objekts sein, andernfalls wird eineIllegalMonitorStateException-Ausnahme ausgelöst.

Wenn der aktuelle Thread vor oder während des Wartens von einem beliebigen Thread unterbrochen wird, wird eineInterruptedException-Ausnahme ausgelöst.

Syntax

public final void wait()

Parameters

  • Keine 。

Rückgabewert

Kein Rückgabewert.

Beispiel

Das folgende Beispiel demonstriert die Verwendung der wait()-Methode:

Beispiel

import java.util.Collections; import java.util.LinkedList; import java.util.List; public class ExampleTest extends Object { private List synchedList; public ExampleTest() { //Synchronisierte Liste erstellen synchedList = Collections.synchronizedList(new LinkedList()); } //Ein Element aus der Liste entfernen public String removeElement() throws InterruptedException { synchronized (synchedList) { //Warte, wenn die Liste leer ist while (synchedList.isEmpty()) { System.out.println("Liste ist leer..."); synchedList.wait(); System.out.println("Warte..."); } String element = (String) synchedList.remove(0); return element; } } //Füge ein Element zur Liste hinzu public void addElement(String element) { System.out.println("Öffnen..."); synchronized (synchedList) { //Ein Element hinzufügen und benachrichtigen, dass das Element existiert synchedList.add(element); System.out.println("Neues Element:'" + element + "'"); synchedList.notifyAll(); System.out.println("notifyAll aufgerufen!"); } System.out.println("Schließen..."); } public static void main(String[] args) { final ExampleTest demo = new ExampleTest(); Runnable runA = new Runnable() { public void run() { try { String item = demo.removeElement(); System.out.println("" + item); } catch (InterruptedException ix) { System.out.println("Unterbrochene Ausnahme!"); } catch (Exception x) { System.out.println("Ausnahme ausgelöst."); } } }; Runnable runB = new Runnable() { //Führe die Operation zum Hinzufügen des Elements aus und starte die Schleife public void run() { demo.addElement("Hallo!"); } }; try { Thread threadA1 = new Thread(runA, "Google"); threadA1.start(); Thread.sleep(500); Thread threadA2 = new Thread(runA, "Example"); threadA2.start(); Thread.sleep(500); Thread threadB = new Thread(runB, "Taobao"); threadB.start(); Thread.sleep(1000); threadA1.interrupt(); threadA2.interrupt(); } catch (InterruptedException x) { } } }

Die Ausgabe des obigen Programms ist:

List is empty...
List is empty...
Opening...
New Element:'Hello!'
notifyAll called!
Closing...
Waiting...
Waiting...
List is empty...
Hello!
Interrupted Exception!

Java String类Java Object-Klasse

Andere Erweiterungen