使用BlockQueue,模仿写一个生成者和消费者demo

package com.dnaer.core.sale.saleinvitelog.util;

import ch.qos.logback.core.util.TimeUtil;

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

class Producer {

    public static volatile Boolean TAG = false;

    private AtomicInteger atomicInteger =new AtomicInteger(0);


    private BlockingQueue<Integer> blockingQueue;
    public Producer (BlockingQueue<Integer> blockingQueue) {
        this.blockingQueue = blockingQueue;
    }


    public void pro(){
        while (TAG) {
            try {
                int value =  atomicInteger.incrementAndGet();
                blockingQueue.offer(value,2,TimeUnit.SECONDS);
                System.out.println("生产者:t1"+" , 生产数据"+value);
                TimeUnit.MILLISECONDS.sleep(100);
            }catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    public void cons() {
        while (TAG) {
            try {
                Integer value =(Integer) blockingQueue.poll(2,TimeUnit.SECONDS);
                if (value == null) {
                    TAG = false;
                    System.out.println("\t\t消费者,t2"+"取消监听");
                }else {
                    System.out.println("\t\t消费者,t2"+"获取数据:"+value);
                }
            }catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

}




public class ProAndConsumerThreadTest {

    public static void main(String[] args) throws  Exception{

        TimeUnit.SECONDS.sleep(1);

        try {
            ArrayBlockingQueue<Integer> arrayBlockingQueue =new ArrayBlockingQueue<>(3);
            Producer.TAG =true;
            Producer producer = new Producer(arrayBlockingQueue);
            new Thread(() ->{
                producer.pro();
            }).start();

            new Thread(() ->{
                producer.cons();
            }).start();

        }catch (Exception e) {
            e.printStackTrace();
        }


        TimeUnit.SECONDS.sleep(3);
        Producer.TAG = false;

    }

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值