新浪笔试题,生产消费者,它是不是出错了😣
新浪笔试题,生产消费者,它是不是出错了😣 我注释掉的部分是我加的,原题上没有,填五个空,如果没有我加的else,实在不知道怎么阻塞消费者线程,remove函数恒执
import java.util.List;
public class A implements Runnable {
private final List<Data> queue;
public A(List<Data> queue) {
this.queue = queue;
}
//消费者
public void run(){
try {
while (true) {
synchronized (queue) {
if(queue.size()==0){ //1 如果可用数据为0
System.out.println("可用数据为空,需要生产者生产"); //2
queue.notifyAll();
}else{
Data data = queue.remove(0);
System.out.println(data.getData());
}
}
Thread.sleep(1000);
}
} catch (InterruptedException e){
e. printStackTrace();
}
}
}
import java.util.List;
public class B implements Runnable {
private final List<Data> queue;
private final int length; //缓存最大值
public B(List<Data> queue,int length) {
this.queue=queue;
this.length = length;
}
//生产者 逻辑if else暗含一个wait() notifyAll() 而queue并不能判断阻塞唤醒的是哪个,所以借助if else完成一个,至于要显示 的写哪个,消费者中的queue.notifyAll(); 是题眼,说明阻塞和唤醒的是生产者
public void run() {
try{
while (true) {
synchronized (queue) {
if( queue.size()==length ){ //3 队列已满
queue.wait(); //4 阻塞自己不在生产
System.out.println("队列已满,需要消费者消费"); //5
}
// else{
Data data = new Data();
queue.add(data);
//}
}
Thread.sleep(1000);
}
} catch (InterruptedException e) {
e. printStackTrace();
}
}
}
#微博#