新浪笔试题,生产消费者,它是不是出错了😣

新浪笔试题,生产消费者,它是不是出错了😣 我注释掉的部分是我加的,原题上没有,填五个空,如果没有我加的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();

}

}
}
#微博#
全部评论
填空12345,我已经填好了
点赞 回复 分享
发布于 2018-12-08 20:55

相关推荐

点赞 评论 收藏
分享
评论
点赞
1
分享

创作者周榜

更多
牛客网
牛客企业服务