首页 新闻 会员 周边

java生产者和消费者同步问题

0
悬赏园豆:50 [已关闭问题] 关闭于 2015-06-27 15:55

今天在看生产者和消费者同步的时候。结果总是不理想,上代码先。

public class Test {

    public static void main(String[] args) {
        Baozi baozi = new Baozi();
        new Thread(new Producer(baozi)).start();
        new Thread(new Consumer(baozi)).start();
    }

}

class Baozi{
    private int count;
    private boolean bFull = false;
    
    public synchronized void putBaozi(int i){
        if(!bFull){
            this.count = i;
            bFull = true;
            notify();
        }
        try {
            wait();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
    
    public synchronized int getBaozi(){
        if(!bFull){
            try {
                wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        
        bFull = false;
        notify();
        return count;
    }
}

class Producer implements Runnable{
    private Baozi bz;
    
    public Producer(Baozi bz) {
        this.bz = bz;
    }
    @Override
    public void run() {
        for (int i = 1; i <= 10; i++) {
            bz.putBaozi(i);
            System.out.println("老板蒸了第"+i+"个包子");
        }
    }
    
}

class Consumer implements Runnable{
    private Baozi bz;
    
    public Consumer(Baozi bz) {
        this.bz = bz;
    }
    @Override
    public void run() {
        while(true){
            System.out.println("学生妹买了第"+ bz.getBaozi() + "个包子");
        }
    }
    
}
View Code

运行结果有2中情况

1、错误情况

学生妹买了第1个包子
老板蒸了第1个包子
学生妹买了第2个包子
老板蒸了第2个包子
...

2、正确情况

老板蒸了第1个包子
学生妹买了第1个包子
老板蒸了第2个包子
学生妹买了第2个包子
...

每次刷新,错误的情况反而出现的多一些。

getBaozi() 方法里面,没有包子的时候,明明就wait() 了。  为什么老板都没开始卖,妹子却能买到包子呢?

不要呵呵的主页 不要呵呵 | 初学一级 | 园豆:124
提问于:2015-06-27 15:23
< >
分享
清除回答草稿
   您需要登录以后才能回答,未注册用户请先注册