基于阻塞队列的生产者消费者模式

对于多线程下的生产者消费者模式

线程操作资源类

判断,干活,唤醒

1:定义一个资源类

class ShareResource {
    private Boolean FLAG = true;
    BlockingQueue blockingDeque = null;
    AtomicInteger i = new AtomicInteger();

    public shareResource(BlockingQueue blockingDeque) {
        this.blockingDeque = blockingDeque;
    }

    public void myProd() {
        while (FLAG) {
            String data = i.incrementAndGet() + "";
            try {
                boolean offer = blockingDeque.offer(data, 2L, TimeUnit.SECONDS);
                if (offer) {
                    System.out.println(Thread.currentThread().getName() + "\t" + "成功生产一个");
                } else {
                    System.out.println(Thread.currentThread().getName() + "\t" + "插入失败");
                }
                TimeUnit.SECONDS.sleep(1);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
       }
        System.out.println("FLAG = " + FLAG + "大老板叫停");
    }

    public void myconsum() {
        while (FLAG) {
            String data = i.incrementAndGet() + "";
            try {
                String poll = (String) blockingDeque.poll(2L, TimeUnit.SECONDS);
                if (poll == null || poll.equalsIgnoreCase("")) {
                    System.out.println(Thread.currentThread().getName() + "获取失败");
                } else {
                    System.out.println(Thread.currentThread().getName() + "成功获得消息");
                }
                TimeUnit.SECONDS.sleep(1);
            } catch (Exception e) {

            }

        }
        System.out.println("FLAG = " + FLAG + "大老板叫停");
    }

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

在资源类中定义一个Flag,作为生产消费的总开关,方便控制消息的生产和消费

2:在mian方法中调用资源量

public class ProdAndConQueue {
    public static void main(String[] args) {
        BlockingQueue queue = new ArrayBlockingQueue(1);

        shareResource shareResource = new shareResource(queue);

        new Thread(new Runnable() {
            @Override
            public void run() {
                shareResource.myProd();
            }
        },"prod").start();

        new Thread(new Runnable() {
            @Override
            public void run() {
                shareResource.myconsum();
            }
        },"consumer").start();

        try {
            TimeUnit.SECONDS.sleep(5);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        shareResource.stop();
    }
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值