Java Object notifyAll() 方法

介绍

Java中的Object类是所有类的祖先,其中包含了wait()、notify()和notifyAll()等方法,用于线程之间的通信。notifyAll()方法允许一个线程在等待时被唤醒,以便重新竞争资源。

示例

下面是一个使用notifyAll()方法的简单示例:

public class WaitNotifyDemo {
    public static void main(String[] args) {
        Message msg = new Message("Process it");
        Waiter waiter1 = new Waiter(msg);
        new Thread(waiter1,"waiter1").start();
        Waiter waiter2 = new Waiter(msg);
        new Thread(waiter2, "waiter2").start();
        Notifier notifier = new Notifier(msg);
        new Thread(notifier, "notifier").start();
        System.out.println("All the threads are started");
    }
}

class Message {
    private String msg;

    public Message(String str){
        this.msg=str;
    }

    public String getMsg() {
        return msg;
    }

    public void setMsg(String str) {
        this.msg=str;
    }
}

class Waiter implements Runnable{

    private Message msg;

    public Waiter(Message m){
        this.msg=m;
    }

    public void run() {
        String name = Thread.currentThread().getName();
        synchronized (msg) {
            try{
                System.out.println(name+" waiting to get notified at time:"+System.currentTimeMillis());
                msg.wait();
            }catch(InterruptedException e){
                e.printStackTrace();
            }
            System.out.println(name+" waiter thread got notified at time:"+System.currentTimeMillis());
            System.out.println(name+" processed: "+msg.getMsg());
        }
    }
}

class Notifier implements Runnable {

    private Message msg;

    public Notifier(Message msg) {
        this.msg = msg;
    }

    public void run() {
        System.out.println("Notifier started");
        try {
            Thread.sleep(1000);
            synchronized (msg) {
                msg.setMsg("Notifier work done");
                //msg.notify();   // notify only one thread
                msg.notifyAll(); // notify all waiting threads
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

    }
}

运行以上代码将输出以下结果:

All the threads are started
waiter1 waiting to get notified at time:1629310441023
waiter2 waiting to get notified at time:1629310441023
Notifier started
waiter2 waiter thread got notified at time:1629310442024
waiter2 processed: Notifier work done
waiter1 waiter thread got notified at time:1629310442024
waiter1 processed: Notifier work done

解释

在上面的示例中,我们定义了一个Message类,该类包括一个消息。Waiter和Notifier类实现了Runnable接口。Waiter类等待消息,Notifier类发送消息。

Waiter类使用wait()方法等待消息,当Notifier类发送消息时,它使用notifyAll()方法通知所有等待的线程,这将使所有等待的线程进入可运行状态,并且它们将竞争资源。

在这里,我们定义了两个Waiter线程,这意味着它们都等待同一消息,当Notifier发送消息并使用notifyAll()方法通知所有等待的线程时,两个Waiter线程都被唤醒。

总结

使用notifyAll()方法可以避免线程无限期地等待,它可以唤醒所有等待的线程,让它们重新竞争资源。这使得代码更加健壮,并且可以避免死锁问题。

然而,使用notifyAll()方法也需要小心,如果你通知了太多的线程,这可能会导致性能问题。因此,在使用notifyAll()方法时,请确保只唤醒必要的线程。

本文来源:词雅网

本文地址:https://www.ciyawang.com/46b5h0.html

本文使用「 署名-非商业性使用-相同方式共享 4.0 国际 (CC BY-NC-SA 4.0) 」许可协议授权,转载或使用请署名并注明出处。

相关推荐