java之BlockingQueue实现生产者消费者

直接上代码
注意在使用blockingqueue实现生产者消费者模型时候,BlockingQueue泛型使用若atomic等对象时候会发现消费者出现异常,这是由于传值和传引用的区别,而Integer由于java的自动装箱不会出现此类问题,具体可自行尝试

生产者

public class Pull implements Runnable {

    BlockingQueue<Integer> pool;

    Integer product = 0;

    public Pull(BlockingQueue<Integer> pool) {
        this.pool = pool;
    }

    @Override
    public void run() {
        while (true) {
            try {
                pool.put(product);
                System.out.println("add:" + product);
                product++;
            } catch (InterruptedException e) {
                System.out.println("add failed");
                e.printStackTrace();
            }

            if (product == 20){
                break;
            }

        }
    }
}

消费者

public class Push implements Runnable{

    BlockingQueue<Integer> pool;

    public Push(BlockingQueue<Integer> pool) {
        this.pool = pool;
    }

    @Override
    public void run() {

        while(true) {
            try {
                Integer tmp = pool.take();
                System.out.println("take:" + tmp);
            } catch (InterruptedException e) {
                System.out.println("获取失败");
                e.printStackTrace();
            }
        }
    }
}

主线程

public class MyExecutor {
    public static void main(String[] args) {
        BlockingQueue<Integer> queue = new LinkedBlockingDeque<>(10);
        Thread thread = new Thread(new Push(queue));
        Thread thread1 = new Thread(new Pull(queue));
        thread1.start();
        thread.start();
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值