生产者与消费者问题(JAVA实现)

youhebuke52011 2015-08-10 05:55:44
public class TestProducerConsumer{
public static void main(String[] agrs){
SyncStack ss = new SyncStack();
Producer p = new Producer(ss);
ConSumer c = new ConSumer(ss);
new Thread(p).start();
new Thread(c).start();

}
}

class Woto{

int id;
public Woto(int id){
this.id = id;
}

public String toString(){
return "Woto:" + id;
}
}
class SyncStack{
int index = 0;
Woto[] w = new Woto[8];

public synchronized void push(Woto wt){
while(index == w.length){
try {
this.wait();
} catch (InterruptedException e) {

e.printStackTrace();
}
}
this.notify();
w[index] = wt;
index++;
}

public synchronized Woto pop(){
while(index == 0){
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
this.notify();
index--;
return w[index];
}
}

class Producer implements Runnable{
SyncStack ss = null;
public Producer(SyncStack ss){
this.ss = ss;
}

public void run() {
for(int i = 0;i<10;i++){
Woto wt = new Woto(i);
ss.push(wt);
System.out.println("生产了="+wt);
try {
Thread.sleep((int) (Math.random() * 200));
} catch (InterruptedException e) {

e.printStackTrace();
}
}
}
}

class ConSumer implements Runnable{
SyncStack ss = null;
public ConSumer(SyncStack ss){
this.ss = ss;
}

public void run() {
for(int i = 0;i<10;i++){

Woto wt =ss.pop();
System.out.println("消费了="+wt);
try {
Thread.sleep((int) (Math.random() * 1000));
} catch (InterruptedException e) {
e.printStackTrace();
}

}
}
}


为什么会先出现消费者呢 ?求大神解答



求解决办法
...全文
107 4 打赏 收藏 转发到动态 举报
写回复
用AI写文章
4 条回复
切换为时间正序
请发表友善的回复…
发表回复
猪哥66 2015-08-11
  • 打赏
  • 举报
回复
而且应该是生产一个消费一个对吧,你觉得呢,生产1消费1生产2消费2
猪哥66 2015-08-11
  • 打赏
  • 举报
回复
你的代码阅读性太差,你为什么不将生产和消费线程封装在一个类中,然后外面用生产了和消费了调用两个方法呢?这样提高了代码的复用性
youhebuke52011 2015-08-10
  • 打赏
  • 举报
回复
引用 1 楼 shijing266 的回复:
你的c 和p 相当于起了两个线程,这是异步的,而你的Producer 执行push();的速度慢于ConSumer执行pop();的速度 所以消费在先咯
soga ,我知道 谢谢
  • 打赏
  • 举报
回复
你的c 和p 相当于起了两个线程,这是异步的,而你的Producer 执行push();的速度慢于ConSumer执行pop();的速度 所以消费在先咯

50,504

社区成员

发帖
与我相关
我的任务
社区描述
Java相关技术讨论
javaspring bootspring cloud 技术论坛(原bbs)
社区管理员
  • Java相关社区
  • 小虚竹
  • 谙忆
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧