avatar
java synchronized 问题# Programming - 葵花宝典
j*g
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
avatar
s*u
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 (...){};

avatar
j*g
3
getInt的wait好像应该由putInt的notifyAll来释放吧?
avatar
m*t
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来释放吧?
avatar
j*g
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?
avatar
m*t
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?

avatar
j*g
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?
avatar
g*g
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?

相关阅读
logo
联系我们隐私协议©2024 redian.news
Redian新闻
Redian.news刊载任何文章,不代表同意其说法或描述,仅为提供更多信息,也不构成任何建议。文章信息的合法性及真实性由其作者负责,与Redian.news及其运营公司无关。欢迎投稿,如发现稿件侵权,或作者不愿在本网发表文章,请版权拥有者通知本网处理。