在这段代码中,我试图实现生产者-消费者模式。问题出现在预期之外 - 当您运行此代码时,方法中出现错误get():
此方法必须返回 int 类型的结果
我怀疑这是因为它return隐藏在循环中,而不是因为它会被调用?那么如何修复此代码,以便两个线程交替服务并返回值n?
public class ProdCons2 {
public static void main(String[] args) {
Q q = new Q();
new Producer(q);
new Consumer(q);
}
}
class Q{
int n;
boolean valueSet = false;
synchronized int get(){
while(!valueSet){
try{
wait();
} catch (InterruptedException e){}
System.out.println("Получено: " + n);
valueSet = false;
notify();
return n;
}
}
synchronized void put(int n){
while (valueSet){
try{
wait();
} catch (InterruptedException e){}
this.n = n;
System.out.println("Отправлено: " + n);
valueSet = true;
notify();
}
}
}
class Producer implements Runnable{
Q q;
static int i = 0;
Producer(Q q){
this.q = q;
new Thread(this, "Поставщик").start();
}
public void run(){
while(i<200){
q.put(i++);
}
}
}
class Consumer implements Runnable{
Q q;
Consumer(Q q){
this.q=q;
new Thread(this, "Потребитель").start();
}
public void run(){
{
while(Producer.i<200){
q.get();
}
}
}
}
将代码移出循环