Queue

jdk对Queue接口有自己的实现,在concurrent包中,子接口BlockingQueue定义了Queue所有的特性。

put和take是两个阻塞方法。当put值但队列已满时阻塞,take值但队列为空时阻塞。

以ArrayBlockQueue为例

1、生产者

public class Producer implements Runnable {

    private BlockingQueue queue;

    public Producer(BlockingQueue queue) {
        this.queue = queue;
    }

    @Override
    public void run() {

        for (int i = 0; i < 10; i++) {
            try {
                queue.put(i);
                System.out.println("我放进去了" + i);
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        try {
            Thread.sleep(6000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        queue.add(666);
        System.out.println("我放进去了666");
    }
}


2、消费者

public class Customer implements Runnable {

    private BlockingQueue queue;

    public Customer(BlockingQueue queue) {
        this.queue = queue;
    }

    @Override
    public void run() {
        while (true) {
            try {
                System.out.println("我拿出来了" + queue.take());
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}

3、输出

public class BlockingQueueExample {

    public static void main(String[] args) {

        BlockingQueue blockingQueue = new ArrayBlockingQueue(5);
        Producer producer = new Producer(blockingQueue);
        Customer customer = new Customer(blockingQueue);

        new Thread(producer).start();
        new Thread(customer).start();
    }
}




                
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值