gpt4 book ai didi

java - 线程仍在等待

转载 作者:行者123 更新时间:2023-12-01 08:52:10 25 4
gpt4 key购买 nike

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();

noitified

最佳答案

wait()之前调用notifyAll(),因此“信号”丢失。这就是为什么在使用 wait/notify 时需要条件变量。

boolean produced = false;
// In producer
produced = true;
asd.notifyAll();

// in consumer
while(!produced)
wait();

关于java - 线程仍在等待,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42320601/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com