java面试总结08_生产者消费者实例

面试的过程中,经常让写个消费者-生产者实例,这里有一个简单的实例:

阻塞队列的:

消费者:

public class Consumer implements Runnable {
    /**
     * 所有的数据会存在blockingDeque 里面,取blockingDeque就行
     */
    private final BlockingQueue<Integer> blockingQeque;

    public Consumer(BlockingQueue block) {
        this.blockingQeque = block;
    }

    @Override
    public void run() {
        while (true) {
            //模拟耗时
            try {
                Thread.sleep(1000);
                decream(blockingQeque.take());
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    private void decream(int a) {
        System.out.println("thread name:" + Thread.currentThread().getName() + " 消耗:" + a);
    }
}

生产者:

public class Product implements Runnable {
    private final BlockingQueue<Integer> blockingQeque;

    public Product(BlockingQueue block) {
        this.blockingQeque = block;
    }

    @Override
    public void run() {
        while (true) {
            try {
                blockingQeque.put(incream());
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }

    }

    private int incream() {
        int a = new Random().nextInt(10);
        System.out.println("thread name:" + Thread.currentThread().getName() + " incream:" + a);
        return a;
    }
}
public static void main(String[] args) {

        BlockingQueue<Integer> blockQueue=new ArrayBlockingQueue<Integer>(10);
        Product product=new Product(blockQueue);
        Consumer consumer1=new Consumer(blockQueue);
        Consumer consumer2=new Consumer(blockQueue);
        new Thread(product).start();
        new Thread(consumer1).start();
        new Thread(consumer2).start();
    }

运行结果:

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值