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()
Thread еще ждет
После PTHREAD делается с его уведомлением работы, то cThread продолжает ждать бесконечного количества времени. Любая идея, почему prod.sb.wait();
не является noitified по sb.notify();
для синхронизации вам лучше использовать изменчивые атомные переменные. – efekctive