Método wait() en Java con ejemplos

La comunicación entre subprocesos es una forma en la que los subprocesos sincronizados pueden comunicarse entre sí utilizando los métodos a saber, wait(), notificar() y notificar a todos(). El método wait() es parte de la clase java.lang.Object. Cuando se llama al método wait(), el subproceso de llamada detiene su ejecución hasta que algún otro subproceso invoque el método notificar() o notificar a todos().

Sintaxis:

public final void wait() throws InterruptedException

Excepciones

  • InterruptedException : si algún subproceso interrumpió el subproceso actual antes o mientras el subproceso actual esperaba una notificación.
  • IllegalMonitorStateException : si el subproceso actual no es el propietario del monitor del objeto.

Laboral:

  • En Java, los métodos y bloques sincronizados permiten que solo un subproceso adquiera el bloqueo de un recurso a la vez. Entonces, cuando un subproceso llama al método wait(), entonces abandona el bloqueo de ese recurso y se va a dormir hasta que otro subproceso ingresa al mismo monitor e invoca el método de notificación() o de notificación a todos().
  • Llamar a notificar() activa solo un hilo y llamar a notificar a Todos() activa todos los hilos en el mismo objeto. Llamar a estos dos métodos no libera el bloqueo del recurso, sino que su trabajo es despertar los subprocesos que se han enviado al estado de suspensión mediante el método wait().
  • Una gran diferencia entre el método sleep() y el método wait() es que el método sleep() hace que un subproceso entre en reposo durante un período de tiempo específico, mientras que wait() hace que el subproceso entre en reposo hasta que se invoquen las notificaciones() y notificar a Todos().

En el código que se menciona a continuación, hemos creado una clase GunFight que contiene una variable miembro bullets que se inicializa en 40 y dos métodos fire() y reload(). El método fire() dispara la cantidad de viñetas que se le pasan hasta que las viñetas se vuelven 0 y cuando las viñetas se vuelven 0, invoca el método wait() que provocó que el subproceso de llamada se suspendiera y liberara el bloqueo del objeto mientras que el método reload() aumentaba las viñetas por 40 e invoca el método de notificación() que despierta el hilo en espera.

Java

// Java program to demonstrate the use of wait() method
class GunFight {
    private int bullets = 40;
  
    // This method fires the number of bullets that are
    // passed it. When the bullet in magazine becomes zero,
    // it calls the wait() method and releases the lock.
    synchronized public void fire(int bulletsToBeFired)
    {
        for (int i = 1; i <= bulletsToBeFired; i++) {
            if (bullets == 0) {
                System.out.println(i - 1
                                   + " bullets fired and "
                                   + bullets + " remains");
                System.out.println(
                    "Invoking the wait() method");
                try {
                    wait();
                }
                catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println(
                    "Continuing the fire after reloading");
            }
  
            bullets--;
        }
        System.out.println(
            "The firing process is complete");
    }
  
    // reload() increases the bullets by 40 everytime it is
    // invoked and calls the notify() method which wakes up
    // the thread that was sent to sleep using wait() inside
    // of fire() method
    synchronized public void reload()
    {
        System.out.println(
            "Reloading the magazine and resuming "
            + "the thread using notify()");
        bullets += 40;
        notify();
    }
}
  
public class WaitDemo extends Thread {
    public static void main(String[] args)
    {
  
        GunFight gf = new GunFight();
  
        // Creating a new thread and invoking
        // our fire() method on it
        new Thread() {
            @Override public void run() { gf.fire(60); }
        }.start();
  
        // Creating a new thread and invoking
        // our reload method on it
        new Thread() {
            @Override public void run() { gf.reload(); }
        }.start();
    }
}
Producción

40 bullets fired and 0 remains
Invoking the wait() method
Reloading the magazine and resuming the thread using notify()
Continuing the fire after reloading
The firing process is complete

Publicación traducida automáticamente

Artículo escrito por shivamsingh00141 y traducido por Barcelona Geeks. The original can be accessed here. Licence: CCBY-SA

Deja una respuesta

Tu dirección de correo electrónico no será publicada. Los campos obligatorios están marcados con *