【问题标题】:Why boolean variable after While loop still true?为什么 While 循环后的布尔变量仍然为真?
【发布时间】:2020-07-30 08:06:00
【问题描述】:

我对这些方法理解有问题,还有变量empty

    private String message;
    private boolean empty = true;

    public synchronized String read() {

        while (empty) {
            try {
                wait();
            } catch (InterruptedException e) {}
        }

        empty = true; // i mean this line

        notifyAll();
        return message;
    }

    public synchronized void write(String message) {

        while (!empty) {
            try {
                wait();
            } catch (InterruptedException e) {}
        }

        empty = false; // and this line

        this.message = message;
        notifyAll();
    }

首先我无法理解wait()notifyAll(),其次为什么在read()的while循环之后,空为真,何为假? 与 write() 相同,为什么在 while 循环之后不为真?

对不起,如果我的语言不好,我不是母语人士。

【问题讨论】:

  • 想象一下,如果 empty 被重命名为 messageConsumed。是不是更清楚了?
  • @VGR 还没有,为什么在 while 循环块之后,在 write() 中仍然正确?
  • 因为write方法必须等待消息被读取。一旦被读取,布尔字段设置为 false,表示有新消息可供阅读。

标签: java multithreading concurrency wait notify


【解决方案1】:

它的顺序有点奇怪 - 例如,我会在修改“消息”之后修改“空”,这对我来说似乎更明显 - 但是......

这是一个单消息缓冲区。

'write' 方法一直等到 'empty',此时它可以将消息设置为 'message',使其不为空。

'read' 方法一直等到 'not empty',此时它可以使用来自 'message' 的消息,使其再次为空。

根据我的口味,变量“空”是多余的。我将它基于“消息”的空/非空状态(假设从来没有将空写为消息的情况)。

【讨论】:

    【解决方案2】:

    只要empty 为真,read 就会调用wait:意味着没有什么可读的。一旦empty 为假,readempty 设置为真(意味着它读取任何要读取的内容),通知所有等待的线程并返回。

    write 正好相反。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-01-12
      • 1970-01-01
      • 1970-01-01
      • 2016-04-02
      • 2020-02-01
      • 1970-01-01
      相关资源
      最近更新 更多