【发布时间】:2016-12-26 14:48:10
【问题描述】:
所以我一直在用 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块中,否则您永远不会知道是否发生了异常。 -
注意:Java 语言约定类名以大写名称开头(因此,
producer不是一个好的类名)。类、方法或包名称中不使用下划线,仅在全大写的常量名称中使用下划线。类的名称类似于ThreadCommunication,而不是Tread_Comunication。还建议给变量起有意义的名称,而不是 'p' 和 'pp'。 -
关闭投票者:发布的代码确实重现了问题(至少尽可能多地重现,因为代码取决于调度程序可能会或可能不会发生的竞争条件)。在发布的代码和显示的输出之间,弄清楚这里发生了什么是切实可行的。
标签: java multithreading wait synchronized notify