多生产多消费

import java.util.concurrent.locks.*;

class BoundedBuffer {
    private final Lock lock = new ReentrantLock();
    //创建监视器对象,每个监视器对象对应一个FIFO队列
    private final Condition notFull  = lock.newCondition();
    private final Condition notEmpty = lock.newCondition();

    //容器
    private final int[] items = new int[100];
    private int putptr, takeptr, count;//容器角标     数量

    public void put() throws InterruptedException {
        lock.lock();
        try {
            while (count == items.length)
                notFull.await();
            items[putptr] = putptr;//填充数字
            if (++putptr == items.length) putptr = 0;
            ++count;
            System.out.println(Thread.currentThread().getName()+"---生产第"+putptr+"个容器里的----总共"+count);
            notEmpty.signal();
        } finally {
            lock.unlock();
        }
    }

    public void take() throws InterruptedException {
        lock.lock();
        try {
            while (count == 0)
                notEmpty.await();
            takeptr = items[takeptr];
            if (++takeptr == items.length) takeptr = 0;
            --count;
            System.out.println(Thread.currentThread().getName()+"---消费第"+takeptr+"个容器里的----还剩"+count);
            notFull.signal();
        } finally {
            lock.unlock();
        }
    }
}

//2.描述生产者
class Produce implements Runnable{
    private BoundedBuffer b;
    //生产者一初始化就要有资源,需要将资源传递到构造函数中。
    Produce(BoundedBuffer b){
        this.b = b;
    }

    @Override
    public void run() {
        while (true){
            try {
                b.put();
            }catch (InterruptedException e){}
        }

    }
}

//3.描述消费者
class Consume implements Runnable{
    private BoundedBuffer b;
    //消费者一初始化就要有资源,需要将资源传递到构造函数中。
    Consume(BoundedBuffer b){
        this.b = b;
    }

    @Override
    public void run() {
        while (true){
            try {
                b.take();
            }catch (InterruptedException e){}
        }
    }
}


public class ThreadExample {
    public static void main(String[] args) {
        BoundedBuffer b = new BoundedBuffer();

        Produce pro = new Produce(b);
        Consume con = new Consume(b);

        Thread t1 = new Thread(pro);
        Thread t2 = new Thread(pro);
        Thread t3 = new Thread(con);
        Thread t4 = new Thread(con);

        t1.start();
        t2.start();
        t3.start();
        t4.start();

    }
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值