关于java.long.Object.notify()
所在版块:求学狮城 发贴时间:2003-11-20 17:15

用户信息
复制本帖HTML代码
高亮: 今天贴 X 昨天贴 X 前天贴 X 
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;
}
};

.
欢迎来到华新中文网,踊跃发帖是支持我们的最好方法!

Put your OWN COOL signature here!
 相关帖子 我要回复↙ ↗回到正文
关于java.long.Object.notify() 我心为谁动   (1687 bytes , 640reads )
Yes, you are right. Flying   (0 bytes , 168reads )
勘误:java.lang.Object.notify() 我心为谁动   (0 bytes , 258reads )