最简单的生产者消费者(wait/notifyAll 实现)(1 生产者1 消费者 仓库大小为1)

一共三个类:Consumer Producer Main

注释都在代码里,不懂的欢迎留言.

消费者

public class Consumer implements Runnable{
    List<Integer> cache;
    Integer num = 10;   //控制次数,否则会无限循环下去无休止.

    public Consumer(List<Integer> cache){
        this.cache = cache;
    }

    @Override
    public void run() {
        while (true){
            synchronized (cache){  //synchronized锁定仓库这个对象,为了避免消费的时候其他线程访问仓库造成错误.
                try{
                    while (cache.size() == 0){//仓库为空的情况下,消费者等待
                        cache.wait();
                    }

                    //能走到这一步说明仓库不为空,开始消费了.
                    System.out.println("消费者消费:"+cache.get( 0 ));
                    cache.remove( 0 );

                    cache.notifyAll();
                    num--;
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}

生产者

public class Producer implements Runnable {
    List<Integer> cache;   //用ArrayList替代仓库,大小为1
    Integer num = 10;      //来控制生产者生产多少次,如果没有这个就会一直不休息的生产.
    Random random = new Random(  );    //用来随机产生物资.

    public Producer(List<Integer> cache){
        this.cache = cache;
    }

    @Override
    public void run() {
        while (num > 0){
            synchronized (cache){
                try {
                    while (cache.size() > 0){
                        cache.wait();        //当仓库中有东西的时候,停止生产.调用wait方法,将该线程放到cache对象的等待池中.
                    }
                    Thread.sleep( 500 );        //可有可无,为了显示出生产消费的变化.
                    Integer integer = random.nextInt(10);
                    cache.add( integer );            //随机产生物资并且放在仓库中
                    System.out.println("生产者生产:"+integer);

                    cache.notifyAll();    //在cache对象的等待池中唤醒正在等待的消费者线程.
                    num--;
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}

主函数

public class Main {
    public static void main(String[] args) {
        List<Integer> list = new ArrayList<>( 1 ); //用来当仓库的ArrayList,大小为1

        Consumer consumer = new Consumer( list );
        Producer producer = new Producer( list );

        Thread thread1 = new Thread( consumer );  //消费者线程
        Thread thread2 = new Thread( producer );  //生产者线程
        thread1.start();
        thread2.start();
    }
}

注释都在代码里,不懂的欢迎留言.

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值