所以我一直在一个简单的等待/在Java中,由于某种原因我一直没能得到它的正常运行通知的例子。如果有人能够看到可能是什么问题,将非常感谢!通知()和notifyAll的()没有在我的Java代码工作
class producer implements Runnable {
StringBuffer sb;
producer() {
sb=new StringBuffer("");
}
public void run() {
synchronized(sb) {
for(int i = 0; i < 10; i++) {
try {
sb.append(i+" ");
System.out.println("Appending ... ");
} catch (Exception e) {}
}
sb.notify();
}
}
}
class consumer implements Runnable {
producer p;
consumer(producer pp) {
this.p = pp;
}
public void run() {
System.out.println("Rreached");
synchronized(p.sb) {
try {
p.sb.wait();
} catch (Exception e) {}
System.out.println(p.sb);
}
}
}
class Thread_Comunication {
public static void main (String [] args) {
producer p = new producer();
consumer c = new consumer(p);
Thread t1 = new Thread(p);
Thread t2 = new Thread(c);
t1.start();
t2.start();
}
}
输出:
Appending ...
Rreached // randome Position
Appending ...
Appending ...
Appending ...
Appending ...
Appending ...
Appending ...
Appending ...
Appending ...
Appending ...
所以出于某种原因线程t1
没有醒t2
还是我失去了别的东西完全?
至少把'e.printStackTrace();'在'catch'块,否则你永远不会知道,如果发生异常。 – Jesper
注意:Java语言约定是类名以大写字母开头(因此'producer'不是一个好的类名)。在类,方法或包名称中不使用下划线,只用于全部为大写的常量名称。类具有像“ThreadCommunication”这样的名称,而不是“Tread_Comunication”。还建议赋予变量有意义的名称,而不是'p'和'pp'。 – RealSkeptic
关闭投票人:发布的代码确实重现了问题(至少尽可能地多,因为代码取决于可能或可能不会发生在调度程序的判断的竞争条件)。在发布的代码和显示的输出之间,找出这里发生的事情是很实际的。 –