java多消费者重复消费问题解决

主要是判断条件 从if 换成 while

1.生产者

public class Productor extends Thread {
    Syncontainer syncontainer;

    public Productor(Syncontainer syncontainer) {
        this.syncontainer = syncontainer;
    }

    @Override
    public void run() {
        try {
            this.syncontainer.push(new Chicken(Thread.currentThread().getId()));
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
    }
}

2.消费者

public class Consumer extends Thread{

    Syncontainer syncontainer;

    public Consumer(Syncontainer syncontainer) {
        this.syncontainer = syncontainer;
    }

    @Override
    public void run() {
        try {
            this.syncontainer.pop();
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
    }
}

3.生产对象

public class Chicken {
    long id;

    public Chicken(long id) {
        this.id = id;
    }

    public long getId() {
        return this.id;
    }
}

4.缓冲区

public class Syncontainer {
    //产品容器缓冲区容量10
    Chicken[] chickens = new Chicken[10];
    int count = 0;

    //放入产品
    public synchronized void push(Chicken chicken) throws InterruptedException {


        //容器满了 不可以再加入
        if (count == chickens.length) {
            System.out.println("装不下了chicken,请等等");
            this.wait();
        }

 //       try {
            chickens[count] = chicken;
            count++;
            System.out.println("生产了chicken:" + chicken.getId());
            this.notify();
//        }catch (Exception e){
//            System.out.println("生产异常线程:"+Thread.currentThread().getName());
//        }


        //

    }

    //消费者消费
    public synchronized void pop() throws InterruptedException {
        System.out.println("消费线程:"+Thread.currentThread().getName());
        while (count <= 0) {
            System.out.println("暂无可消费chicken,请等等");
            this.wait();
        }
 //       try{
            count--;
            System.out.println("消费了chicken:" + chickens[count].getId());
//        }catch (Exception e){
//            System.out.println("消费异常线程:"+Thread.currentThread().getName());
//        }



    }
}

5.运行(使用固定容量线程池)

public class Case1 {
    public static void main(String[] args) {
        ExecutorService e = Executors.newFixedThreadPool(5);
        Syncontainer syncontainer = new Syncontainer();
        for (int i = 0; i < 20; i++) {
            e.execute(new Productor(syncontainer));
            e.execute(new Consumer(syncontainer));
//            new Consumer(syncontainer).start();
//            new Productor(syncontainer).start();

        }
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值