public class Communicate {
public static void main(String... args) {
Producer prod = new Producer();
Consumer cons = new Consumer(prod);
Thread pThread = new Thread(prod, "ProducerThread");
Thread cThread = new Thread(cons, "ConsumerThread");
pThread.start();
cThread.start();
}
}
class Producer extends Thread {
StringBuffer sb;
Producer() { //constructor
sb = new StringBuffer(); //allot memory
}
@Override
public void run() {
synchronized (sb) {
for (int i = 1; i <= 10; i++) {
try {
sb.append("daksh ");
Thread.sleep(100);
System.out.println("appending " + i);
} catch (InterruptedException ex) {
}
}//end of loop
//data production is over, so notify Consumer Thread
System.out.println("Done production");
sb.notifyAll();
}
}
}
class Consumer extends Thread {
Producer prod;
Consumer(Producer production) { //constructor
this.prod = production;
}
@Override
public void run() {
System.out.println("sup");
synchronized (prod.sb) {
//wait till the notification is received from the Producer thread.
try {
System.out.println("waiting");
prod.sb.wait();
} catch (InterruptedException ie) {
}
System.out.println("done");
}
System.out.println(prod.sb);
}
}
我正在尝试使生产和消费者线程与
notify()
进行通信在完成pThread的通知工作之后,cThread会继续等待无限的时间。
任何想法,为什么
prod.sb.wait();
不被sb.notify();
提名 最佳答案
notifyAll()
在wait()
之前被调用,因此“信号”丢失。这就是为什么在使用等待/通知时需要条件变量的原因。
boolean produced = false;
// In producer
produced = true;
asd.notifyAll();
// in consumer
while(!produced)
wait();