我正在嘗試Java線程生產者和消費者程序。 但消費者線程始終處於等待狀態。Java線程生產者和消費者程序問題
我無法調試的問題,爲什麼消費者線程總是轉到待機狀態或生產者未通知消費者線程
請幫我解決這個問題。程序如下。
通信器類調用這兩個生產國和消費類
public class Communicator {
Thread t = null;
Thread t1 = null;
public void runThread() {
Producer p = new Producer();
Consumer c = new Consumer(p);
t = new Thread(p);
t1 = new Thread(c);
t.start();
t1.start();
Thread tr = new Thread() {
public void run() {
for (int i = 0; i < 30; i++) {
System.out.println("t::::::::::::: " + t.getState());
System.out.println("t1::::::::::::: " + t1.getState());
try {
Thread.sleep(2000);
} catch (InterruptedException ie) {
ie.printStackTrace();
}
}
}
};
tr.start();
}
public static void main(String[] args) {
Communicator c = new Communicator();
c.runThread();
}
}
這是生產類數據中追加的StringBuffer,並通知消費者類
public class Producer extends Thread {
public StringBuffer sb;
public Producer() {
sb = new StringBuffer();
}
public void run() {
synchronized (sb) {
try {
System.out.println("Bala");
sb.append("murugan");
sb.notify();
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
下面是消費類代碼。它等待從生產者類獲得通知。
public class Consumer extends Thread {
public Producer p;
public Consumer(Producer p) {
this.p = p;
}
public void run(){
synchronized (p.sb) {
try {
p.sb.wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println(p.sb);
}
}
}
在'Consumer'類中的'wait()'之前,你應該做你的業務邏輯來處理字符串緩衝區中的東西。只有在沒有可用的數據可供處理時,才應該使用wait()。 –
此問題可能會有用:http://stackoverflow.com/questions/37683895/wait-and-notify-in-consumer-and-producer-threads/37686902#37686902。它刪除等待並通過BlokcingQueues通知。用字符串替換Interger –
@ user3509105請參考下面的答案。希望這會有所幫助。方法'notify()'只喚醒那些當前沒有醒來但正在等待通知的符合條件的線程,以便他們能夠獲得鎖。希望它會有所幫助。 –