所以我一直在一個簡單的等待/在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
關閉投票人:發佈的代碼確實重現了問題(至少儘可能地多,因爲代碼取決於可能或可能不會發生在調度程序的判斷的競爭條件)。在發佈的代碼和顯示的輸出之間,找出這裏發生的事情是很實際的。 –