阻塞队列的生产者消费者

阻塞队列的生产者消费者

  • 利用atomicInteger,阻塞队列来完成
package com.xiaojie.jiehe.my;

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * 队列的生产者消费者
 */
public class BlockQueueDemo {
    public static void main(String[] args) {
        MyResource myResource = new MyResource(new ArrayBlockingQueue<>(3));
        new Thread(()->{
            System.out.println("生产者开始");
            myResource.produce();
        },"生产者").start();

        new Thread(()->{
            System.out.println("消费者开始");
            myResource.consumption();
        },"消费者").start();

        try {
            TimeUnit.SECONDS.sleep(5);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        myResource.stop();
        System.out.println("停止");
    }
}

class MyResource{
    private volatile boolean flag = true;//可以生产标志,默认开启
  //生产AtomicInteger,用AtomicInteger可以保证数据的原子性
    AtomicInteger atomicInteger = new AtomicInteger();//默认为0
    BlockingQueue<String> blockingQueue = null;

    public MyResource(BlockingQueue<String> blockingQueue) {//构造方法注入哪种队列
        this.blockingQueue = blockingQueue;
        System.out.println(blockingQueue.getClass().getName());
    }
    //生产者方法
    public void produce(){
        try {
            String i;
            boolean offer = true;
            while (flag){//flag为true生产
                i = atomicInteger.incrementAndGet()+"";
                offer = blockingQueue.offer(i,2L, TimeUnit.SECONDS);//放入前面的加一,两秒放一个
                if (offer){
                    System.out.println(Thread.currentThread().getName()+"\t生产"+i+"成功");
                }else {
                    System.out.println(Thread.currentThread().getName()+"\t生产"+i+"失败");
                }
                TimeUnit.SECONDS.sleep(1);
            }

            System.out.println("生产结束");
        }catch (Exception e){
            e.printStackTrace();
        }

    }
    //消费者方法
    public void consumption(){
        try {
            String i;
            while (flag){//flag为true生产
               i = blockingQueue.poll(2L,TimeUnit.SECONDS);//两秒没取到则不等了
                if (i==null || i.equals("")){
                    flag = false;
                    System.out.println(Thread.currentThread().getName()+"两秒没取到,消费结束");
                    return;
                }
                System.out.println(Thread.currentThread().getName()+"\t消费了"+i);
            }
        }catch (Exception e){
            e.printStackTrace();
        }

    }

    //结束
    public void stop(){
        this.flag = false;
    }
}

在这里插入图片描述

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值