20

wait() 和 notifyAll()的一个设计题

Suppose we wish instead to implement a class of blocking counters;
for such counters, an inc() operation should block only if the counter is maxed
out, and proceed only when it is not. Is the approach below a good one? Explain
why or why not.

public class BoundedCounterThreadSafe {
    private int value;
    private int upperBound;
    public synchronized int current(); // Return value
    public synchronized void reset(); // Reset value to 0
    public synchronized boolean isMaxed(); // Return true if value is maxed out
    public synchronized void inc(); // Increment value if < upperBound
}
public class BlockingCounter {
    private BoundedCounterThreadSafe c;
    ....
    public synchronized void inc() throws InterruptedException {
    while (c.isMaxed()) {
        wait();
    }
    c.inc();
    notifyAll();
}
....
}

题目的意思就是这个设计是不是一个好的设计?为什么?谢谢大神回答!

查看全部
weixin_41335120
weixin_41335120
2018/03/14 04:58
  • 设计
  • thread
  • 点赞
  • 收藏
  • 回答
    私信
满意答案
查看全部

1个回复