我正在java中实现基本的生产者消费者问题 但是当生产者填充缓冲区时,我的代码被挂起并且消费者不会消耗。 下面是代码
import java.util.Vector;
class hi{
static int i;
}
class Producer implements Runnable
{
volatile Vector<Integer>queue;
Producer(Vector<Integer> q)
{
queue=q;
}
public void run()
{
while(true)
{
try{
produce();
}
catch(Exception e)
{
}
}
}
public synchronized void produce() throws InterruptedException
{
while(queue.size()==5)
{
synchronized(queue)
{
queue.wait();
}
}
int t=hi.i++;
Thread.sleep(2000);
System.out.println("adding "+t);
queue.add(t);
queue.notify();
}
}
class Consumer implements Runnable
{
volatile Vector<Integer>queue;
Consumer(Vector<Integer> q)
{
queue=q;
}
public void run()
{
while(true)
{
System.out.println("kaka");
try{
consume();
}
catch(Exception e)
{
}
}
}
public synchronized void consume() throws InterruptedException
{
//Thread.sleep(2000);
while(queue.size()==0)
{
synchronized(queue)
{
queue.wait();
}
}
System.out.println("Removing "+queue.get(0));
queue.remove(0);
queue.notify();
}
}
public class ProducerConsumer {
public static void main(String [] args) throws InterruptedException
{
Vector<Integer>q=new Vector<Integer>();
Producer p=new Producer(q);
Thread p1=new Thread(p);
Consumer c=new Consumer(q);
Thread c1=new Thread(c);
p1.start();
Thread.sleep(2000);
System.out.println("kailash");
c1.start();
}
}
上面我在consume方法中评论了Thread.sleep(2000)。如果我取消注释,代码就可以正常工作。请帮助我理解这个问题。