关于java.long.Object.notify()
Java API doc 对这个method有这么一段叙述:
This method should only be called by a thread that is the owner of this object's monitor. A thread becomes the owner of the object's monitor in one of three ways:
1) By executing a synchronized instance method of that object.
2) By executing the body of a synchronized statement that synchronizes on the object.
3) For objects of type Class, by executing a synchronized static method of that class.
---------------------------------------------------
关于第二点, 请问它的意思是指可以在synchronized的method里面call notify()吗? 比如:
class Buffer {
private String[] buff = new String[8];
private boolean writable = true;
private boolean readable = false;
private int readloc = 0, writeloc = 0;
synchronized void produce (String data) {
while (!writable) {
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
} //end while
buff[writeloc] = data;
readable = true;
writeloc = (writeloc+1)%8;
if (writeloc == readloc) {
writable = false;
}
notify();
}
synchronized String consume () {
while (!readable) {
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
} //end while
writable = true;
String s = buff[readloc];
readloc = (readloc+1)%8;
if (readloc == writeloc) {
readable = false;
}
notify();
return s;
}
};
This method should only be called by a thread that is the owner of this object's monitor. A thread becomes the owner of the object's monitor in one of three ways:
1) By executing a synchronized instance method of that object.
2) By executing the body of a synchronized statement that synchronizes on the object.
3) For objects of type Class, by executing a synchronized static method of that class.
---------------------------------------------------
关于第二点, 请问它的意思是指可以在synchronized的method里面call notify()吗? 比如:
class Buffer {
private String[] buff = new String[8];
private boolean writable = true;
private boolean readable = false;
private int readloc = 0, writeloc = 0;
synchronized void produce (String data) {
while (!writable) {
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
} //end while
buff[writeloc] = data;
readable = true;
writeloc = (writeloc+1)%8;
if (writeloc == readloc) {
writable = false;
}
notify();
}
synchronized String consume () {
while (!readable) {
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
} //end while
writable = true;
String s = buff[readloc];
readloc = (readloc+1)%8;
if (readloc == writeloc) {
readable = false;
}
notify();
return s;
}
};