多线程的消费者/生产者模型中的神坑

 最近在学习多线程的知识,下面的代码是我练手时写的生产者/消费者模型。两个生产者两个消费者共四个线程。

与教学视频的代码一样,但是却有了不同的结果。

package com.java.main;

/**
 * @author:Htc
 * @date: 2019/7/1 13:23
 * @Description:实现资源类
 **/
class Resource{
    private int count=0;//定义资源
    private boolean b=true;//定义生产和消费标记true表示可生成,false表示可消费
    //定义生产
    public synchronized void add(){
        if(!this.b){
            try {
                super.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        this.count++;
        System.out.println(Thread.currentThread().getName()+"生产了一条数据,数据总量为:"+count);
        this.b=false;
        super.notify();

    }
    //定义消费
    public synchronized void sub(){
        if(this.b){
            try {
                super.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        this.count--;
        System.out.println(Thread.currentThread().getName()+"消费了一条数据,数据总量为:"+count);
        this.b=true;
        super.notify();

    }

}
/**
 * @Auther: Htc
 * @Date:2019/7/1 13: 17
 * @Description:实现四个线程操作同一个资源,使用生产者/消费者模型实现
 */
public class ResourceAddSub{
    public static void main(String[] args) {
       Resource resource=new Resource();
        for(int i=0;i<4;i++){
            if(i%2==0){
                new Thread(()->{
                    for(int j=0;j<20;j++){
                        synchronized (resource){
                            resource.sub();
                        }

                    }
                }).start();
            }else{
                new Thread(()->{
                    for(int j=0;j<20;j++){
                        synchronized (resource){
                            resource.add();
                        }
                    }
                }).start();
            }
        }
    }
}


结果一:(预期的结果)

结果二:(非预期结果)本应该是一个生产数据一个消费数据,但是中间却产生了连续的消费数据。这个结果还导致了程序卡死,不能顺利结束运行。

 这个问题让我很困惑。希望有心人解答(或者我后面自己填坑)

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值