java实现生产者、消费者

问题描述:java实现单生产者、单消费者

思路:利用阻塞队列BlockingQueue,生产者生产数据,进入队列,如果阻塞队列已满,达到最大容量,不能再生产数据,消费者消费数据,出队列,如果阻塞队列没有数据,就不能再消费数据。

代码:

public static void main(String[] args) {
        //数组阻塞队列,容量为10
        BlockingQueue list=new ArrayBlockingQueue<Integer>(10);
        Producer thread1=new Producer(list);
        Customer thread2=new Customer(list);
        thread1.start(); //启动生产者线程
        thread2.start();//启动消费者线程
    }
    static class Producer extends Thread{
        private  BlockingQueue<Integer> list;
        Producer(BlockingQueue<Integer> list){
            this.list=list;
        }
        @Override
        public void run(){
            while(true){
                try{
                    int i=new Random().nextInt();
                    list.put(i);//进入阻塞队列,生产数据
                    System.out.println("生产数据"+i);
                    Thread.sleep(200);//控制生产者生产数据的速度
                }catch (InterruptedException e){
                    e.printStackTrace();
                }
            }
        }
    }
    static class Customer extends Thread{
        private  BlockingQueue<Integer> list;
        Customer(BlockingQueue<Integer> list ){
            this.list=list;
        }
        @Override
        public void run(){
            while(true){
                try{
                    int i=list.take();//数据出阻塞队列,消费数据
                    System.out.println("消费数据"+i);
                    Thread.sleep(500);//控制消费者消费数据的速度
                }catch (InterruptedException e){
                    e.printStackTrace();
                }
            }
        }
    }

参考:https://mp.weixin.qq.com/s/o6SMVqxzdTeWlGmnaW_3-g

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值