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();
}
....
}
题目的意思就是这个设计是不是一个好的设计?为什么?谢谢大神回答!
public class BlockingCounter {
private BoundedCounterThreadSafe c;
....
public synchronized void inc() throws InterruptedException {
synchronized(c){//锁定c,保证在Wait前,其它线程都不能修改c
if (c.isMaxed()) {//不用while,while,因为c已经锁定,如果达到max那就直接等待其它线程消费value后唤醒该线程
c.wait();
}
c.inc();
c.notifyAll();//唤醒其它等待消费的线程进行消费
}
}
....
}