j****g 发帖数: 597 | 1 今天看programer_interview看到一个producer-customer并行的问题,用java写的(第7
章section 7.12). Program is written as:
class producer extends Thread {
......
void run() {
while (true) {
try {
putInt();
}
catch (...){};
}
}
private synchronized void putInt() throws ... {
while (index == MAX_CAPACITY) {
wait()
}
buffer[index] = ...
index++;
notifyAll();
}
private synchronized int getInt() throws ... {
notifyAll(); // I ha |
s****u 发帖数: 118 | 2 getint wait了
第7
【在 j****g 的大作中提到】 : 今天看programer_interview看到一个producer-customer并行的问题,用java写的(第7 : 章section 7.12). Program is written as: : class producer extends Thread { : ...... : void run() { : while (true) { : try { : putInt(); : } : catch (...){};
|
j****g 发帖数: 597 | 3 getInt的wait好像应该由putInt的notifyAll来释放吧? |
m******t 发帖数: 2416 | 4
Not necessarily. All the producers and consumers are waiting on the same
object. So a notifyAll from either method would wake up all of them.
【在 j****g 的大作中提到】 : getInt的wait好像应该由putInt的notifyAll来释放吧?
|
j****g 发帖数: 597 | 5 so my question is,
when the buffer is full, and getInt is invoked, it will notifyAll, releasing
the putInt that was blocked on the wait.
If putInt kicks in before getInt could modify the index, then there will be
race condition.
Is that correct? |
m******t 发帖数: 2416 | 6
releasing
be
There won't be.
The putInt thread, after waking up, would have to get hold of the lock
before it can actually resume execution. The getInt thread does _not_
relinguish its ownership on the lock just by calling notifyAll().
【在 j****g 的大作中提到】 : so my question is, : when the buffer is full, and getInt is invoked, it will notifyAll, releasing : the putInt that was blocked on the wait. : If putInt kicks in before getInt could modify the index, then there will be : race condition. : Is that correct?
|
j****g 发帖数: 597 | 7 So does that mean "synchronized" keyword is actually putting lock on the
producer ocject itself but not the method. You can only enter EITHER putInt
OR getInt but you can't enter both from different threads.
right? |
g*****g 发帖数: 34805 | 8 The lock and the monitor is always on object.
putInt
【在 j****g 的大作中提到】 : So does that mean "synchronized" keyword is actually putting lock on the : producer ocject itself but not the method. You can only enter EITHER putInt : OR getInt but you can't enter both from different threads. : right?
|