我实现了生产者消费者问题,但我不明白为什么我的程序停止消费,即使生产者生产请帮助我找到错误并修复。
import java.util.*;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
public class producerConsumer {
private Queue<Integer> queue = new LinkedList<Integer>();
private Random random = new Random();
private synchronized void addData(int data) {
while(queue.size()>=10) ;
queue.add(data);
}
private synchronized int takeData() {
while(queue.size()<=0) ;
return queue.poll();
}
private void producer() {
int data;
while(true) {
data=random.nextInt(100);
addData(data);
System.out.println("the producer produced :"+data);
}
}
private void consumer() {
try {
while(true) {
if(random.nextInt(10)==0) {
Thread.sleep(1000);
System.out.println("The consumed value:"+takeData()+";queue size is "+queue.size());
}
}
}catch(InterruptedException e) {
}
}
public static void main(String args[]) {
producerConsumer pc = new producerConsumer();
pc.process();
}
public void process() {
Thread t1 = new Thread(new Runnable(){
public void run() {
producer();
}
});
Thread t2 = new Thread(new Runnable(){
public void run() {
consumer();
}
});
t1.start();
t2.start();
try {
t1.join();
t2.join();
} catch(InterruptedException e) {
}
}
}