很荣幸成为你口中的“高手”。
这个问题出在notifyAll()的调用上面!
下面是在JDK文档中对Object.notifyAll()方法的描述:
Wakes up a single thread that is waiting on this object's monitor。
注意那个“this”。
也就是说:你的notifyAll()的调用是在C类的this上调用的,所以它
首先必须获得C类this的锁!
既然问题找到了,那么就很容易得出两种改法:
1、C类中的synchronized(A.t)改成:synchronized(this)
当然,我想这不是你要的,因为虽然这样不出错,但是B和C没有在同一个
对象上面同步。
2、C类中的notifyAll();改成:A.t.notifyAll();
我想这才是你真正想要的吧。快试试吧,会有惊喜的。下面是我的实验程序,你可以参考(别忘了给我加分呀~~~):
<pre>
import java.util.*;public class Main{
public static void main(String[] args) { 
new A().go();

} class A{ 
public static Thread t = new B(); 
public static Queue queue = new Queue();
public void go() { 
t.start(); 
new C().start(); 

} class B extends Thread { 
public synchronized void run(){ 
while(true){ 
if(A.queue.isEmpty())
try{
sleep(1000);
wait();
}catch(InterruptedException e){}
else
System.out.println(A.queue.getValues());


} class C extends Thread {
public void run() {
int i = 1;
while(true) {
try{
sleep(2000);
}catch(InterruptedException e){}
A.queue.insert(""+i);
synchronized(A.t){A.t.notifyAll();}
i++;
}
}
}class Queue{
Vector vector = new Vector();
public void insert(String str){
vector.addElement(str);
}
public boolean isEmpty(){
return vector.isEmpty();
}
public String getValues(){
StringBuffer strbuf = new StringBuffer();
for(int i=0; i<vector.size(); i++){
strbuf.append((String)vector.elementAt(i));
}
vector.clear();
return strbuf.toString();
}
}
</pre>