Método notifyAll() de Java Object

Java String类Clase Object de Java


El método notifyAll() de Object se utiliza para despertar todos los hilos que están esperando en ese objeto.

El método notifyAll() es igual queel método notify()La diferencia es que el método notifyAll() despierta a todos los hilos que esperan en el monitor de este objeto, mientras que el método notify() despierta a un solo hilo.

Si el hilo actual no es el propietario del monitor del objeto, llamar al método notifyAll() también provocará unaIllegalMonitorStateExceptionexcepción.

Sintaxis

public final void notifyAll()

Parámetros

  • Ninguno 。

Valor de retorno

No tiene valor de retorno.

Ejemplo

El siguiente ejemplo demuestra el uso del método notifyAll():

Ejemplo

import java.util.Collections; import java.util.LinkedList; import java.util.List; public class EjemploTest { 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 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!

Java String类Clase Object de Java

Otras extensiones