Java 多线程问题,因为尽管使用了等待和通知,生产者-消费者仅执行一次
我已经为线程间通信编写了以下程序,它只是一个接一个地产生和消耗,程序应该一直运行和打印,直到外部停止Java 多线程问题,因为尽管使用了等待和通知,生产者-消费者仅执行一次,java,multithreading,Java,Multithreading,我已经为线程间通信编写了以下程序,它只是一个接一个地产生和消耗,程序应该一直运行和打印,直到外部停止 package multithreading; public class WaitNotifyExample { private final int asd; public WaitNotifyExample(int asd) { this.asd = asd; } public static void main(String[] a
package multithreading;
public class WaitNotifyExample
{
private final int asd;
public WaitNotifyExample(int asd)
{
this.asd = asd;
}
public static void main(String[] args)
{
CounterWaitNotifyExample counter = new CounterWaitNotifyExample(0);
Thread t1 = new Thread(new ConsumerWaitNotifyExample(counter));
Thread t2 = new Thread(new ProducerWaitNotifyExample(counter));
t2.start();
t1.start();
}
}
class ConsumerWaitNotifyExample implements Runnable
{
CounterWaitNotifyExample counter;
public ConsumerWaitNotifyExample(CounterWaitNotifyExample counter)
{
this.counter = counter;
}
@Override
public void run()
{
while (true)
{
counter.consume();
}
}
}
class ProducerWaitNotifyExample implements Runnable
{
CounterWaitNotifyExample counter;
public ProducerWaitNotifyExample(CounterWaitNotifyExample counter)
{
this.counter = counter;
}
@Override
public void run()
{
counter.produce();
}
}
class CounterWaitNotifyExample
{
private int counter;
private boolean produced =false;
public CounterWaitNotifyExample(int counter)
{
this.setCounter(counter);
}
public synchronized void consume()
{
if(!produced)
{
try
{
wait();
} catch (InterruptedException e)
{
e.printStackTrace();
}
}
System.out.println("consumed "+--counter);
produced = false;
notifyAll();
}
public synchronized void produce()
{
if(produced)
{
try
{
wait();
} catch (InterruptedException e)
{
e.printStackTrace();
}
}
System.out.println("produced "+(++counter));
produced = true;
notifyAll();
}
public int getCounter()
{
return counter;
}
public void setCounter(int counter)
{
this.counter = counter;
}
}
但我只得到以下输出,因为应用程序仍在运行,但没有打印任何内容,这意味着,生产者和消费者不再执行
produced 1
consumed 0
我在概念上做错了什么?您的制作人没有任何循环。只有你的消费者有
另外,请阅读
wait()
的javadoc。它必须总是在循环中调用检查条件。我为这样一个愚蠢的错误感到非常羞愧,非常感谢