c******n 发帖数: 4965 | 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 |
f****m 发帖数: 38 | 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(); : } : }
|
q*********u 发帖数: 280 | 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(); : } : }
|
c******n 发帖数: 4965 | 4 the problem is, normal usage of java notify() never mention that the
mutex/lock needs to be the same as the monitor. |
q*********u 发帖数: 280 | 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.
|