加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Java > 正文

java – wait()是“if”块或“while”块

发布时间:2020-12-15 05:03:06 所属栏目:Java 来源:网络整理
导读:参见英文答案 Why should wait() always be called inside a loop????????????????????????????????????8个 以下代码是从 http://www.programcreek.com/2009/02/notify-and-wait-example/复制的 我看过很多使用while循环来包装wait()的例子 我的问题: 在我
参见英文答案 > Why should wait() always be called inside a loop????????????????????????????????????8个
以下代码是从 http://www.programcreek.com/2009/02/notify-and-wait-example/复制的

我看过很多使用while循环来包装wait()的例子

我的问题:
在我第一次尝试解决类似的问题时,我使用if语句来包装wait().例如,

if(messages.size() == MAXQUEUE) {
        wait();
    }

使用while循环而不是if语句有什么好处?

import java.util.Vector;

class Producer extends Thread {

    static final int MAXQUEUE = 5;
    private Vector messages = new Vector();

    @Override
    public void run() {
        try {
            while (true) {
                putMessage();
                //sleep(5000);
            }
        } catch (InterruptedException e) {
        }
    }

    private synchronized void putMessage() throws InterruptedException {
        while (messages.size() == MAXQUEUE) {
            wait();
        }
        messages.addElement(new java.util.Date().toString());
        System.out.println("put message");
        notify();
        //Later,when the necessary event happens,the thread that is running it calls notify() from a block synchronized on the same object.
    }

    // Called by Consumer
    public synchronized String getMessage() throws InterruptedException {
        notify();
        while (messages.size() == 0) {
            wait();//By executing wait() from a synchronized block,a thread gives up its hold on the lock and goes to sleep.
        }
        String message = (String) messages.firstElement();
        messages.removeElement(message);
        return message;
    }
}

class Consumer extends Thread {

    Producer producer;

    Consumer(Producer p) {
        producer = p;
    }

    @Override
    public void run() {
        try {
            while (true) {
                String message = producer.getMessage();
                System.out.println("Got message: " + message);
                //sleep(200);
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    public static void main(String args[]) {
        Producer producer = new Producer();
        producer.start();
        new Consumer(producer).start();
    }
}

解决方法

即使正在等待的对象未被您主动通知,wait()也可能返回(这在 documentation中称为“虚假唤醒”).这就是为什么将wait()调用包装成一个while循环来检查是否满足你想要等待的实际条件并再次调用wait(),而不是简单地假设等待时更合理的原因. )返回您实际等待的事件.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读