Java Object notifyAll()-Methode

Java String类Java Object-Klasse


Die Object.notifyAll()-Methode wird verwendet, um alle Threads aufzuwecken, die auf dieses Objekt warten.

Die notifyAll()-Methode ist ähnlich wie dienotify()-Methode,Der Unterschied besteht darin, dass die notifyAll()-Methode alle Threads aufweckt, die auf den Monitor dieses Objekts warten, während die notify()-Methode einen Thread aufweckt.

Wenn der aktuelle Thread nicht der Besitzer des Monitors des Objekts ist, löst der Aufruf der notifyAll()-Methode ebenfalls eineIllegalMonitorStateExceptionAusnahme aus.

Syntax

public final void notifyAll()

Parameters

  • Keine 。

Rückgabewert

Kein Rückgabewert.

Beispiel

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

Beispiel

import java.util.Collections; import java.util.LinkedList; import java.util.List; public class ExampleTest { private List synchedList; public ExampleTest() { //Erstelle eine synchronisierte Liste synchedList = Collections.synchronizedList(new LinkedList()); } //Ein Element aus der Liste löschen 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