avatar
a fun coding question# Java - 爪哇娇娃
c*n
1
what's wrong with following code?
just try it ...
public class block {
Integer a = new Integer(0);
void dead() throws Exception {
synchronized ( a ) {
while ( a == 0 )
a.wait();
}
}
public void release() {
synchronized(a) {
a = 1;
a.notifyAll();
}
}
public void demo() throws Exception {
new Thread() {
public void run() { try { dead() ; } catch (Exception e )
{System.out.pri
avatar
f*m
2
不就是release()这个method拿不到a的monitor么?

【在 c******n 的大作中提到】
: what's wrong with following code?
: just try it ...
: public class block {
: Integer a = new Integer(0);
: void dead() throws Exception {
: synchronized ( a ) {
: while ( a == 0 )
: a.wait();
: }
: }

avatar
q*u
3
Integers are immutable. If you want to affect the value of a Integer
variable, the only way is to create a new Integer object and discard the old
one.
在你这个
a = 1
a.notifyAll();
这里新的Integer的对象出来了,已经不是原来那个a所指的对象,这个时候在notify,
就会出现illegalMonitorStateException
这个题的确是比较阴险的。

【在 c******n 的大作中提到】
: what's wrong with following code?
: just try it ...
: public class block {
: Integer a = new Integer(0);
: void dead() throws Exception {
: synchronized ( a ) {
: while ( a == 0 )
: a.wait();
: }
: }

avatar
c*n
4
the problem is, normal usage of java notify() never mention that the
mutex/lock needs to be the same as the monitor.
avatar
q*u
5
package multithread;
class SynObject{
public int counter;
public SynObject(){
counter = 0;
}
public SynObject(int cnt){
counter = cnt;
}
}
class Thread3 extends Thread{
public SynObject obj;

public Thread3(SynObject obj){
this.obj = obj;
}

public void run(){
synchronized(obj){
System.out.println("Thread3, before while() lo

【在 c******n 的大作中提到】
: the problem is, normal usage of java notify() never mention that the
: mutex/lock needs to be the same as the monitor.

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