手写一个生产者消费者_阻塞队列。

本文通过使用阻塞队列实现生产者消费者模式,演示了如何在多线程环境下进行资源的生产和消费。代码中,生产者不断生成数据并尝试将其放入队列,而消费者则从队列中取出数据进行处理,当超过指定时间未消费到数据时,系统将停止生产。
class MyResorces {
    private volatile boolean FLAG = true;
    private AtomicInteger atomicInteger = new AtomicInteger();
    BlockingQueue<String> blockingDeque = null;

    //构造器注入
    public MyResorces(BlockingQueue<String> blockingDeque) {
        this.blockingDeque = blockingDeque;
        System.out.println(blockingDeque.getClass().getName());
    }

    public void myProvider() throws InterruptedException {
        String data = null;
        boolean retValue;
        while (FLAG) {
            data = atomicInteger.incrementAndGet() + "";
            retValue = blockingDeque.offer(data, 2L, TimeUnit.SECONDS);
            if (retValue) {
                System.out.println(Thread.currentThread().getName() + "\t 生产者生产了" + data);
            } else {
                System.out.println(Thread.currentThread().getName() + "\t 生产者生产失败了");
            }
            //TimeUnit.SECONDS.sleep(1);
        }
        System.out.println("关门了");
    }

    public void myConsumer() throws InterruptedException {
        String resutl = null;
        while (FLAG) {
            resutl = blockingDeque.poll(2L,TimeUnit.SECONDS);
            if (resutl == null || resutl.equals("")) {
                FLAG = false;
                System.out.println(Thread.currentThread().getName() + "\t 超过了俩秒没消费 把标记改为False告诉生产者别生产了");
                return;
            }
            System.out.println(Thread.currentThread().getName() + "\t 消费者消费了" +resutl);

        }

    }

    public void stop() {
        FLAG = false;
    }
}

public class ProCsu_BlockQueueDemo {
    public static void main(String[] args) {
        MyResorces myResorces = new MyResorces(new ArrayBlockingQueue<>(10));

        new Thread(() -> {
            try {
                myResorces.myProvider();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }, "A").start();
        new Thread(() -> {
            try {
                myResorces.myConsumer();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }, "B").start();

        try {
            TimeUnit.SECONDS.sleep(1);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        myResorces.stop();
    }
}
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值