java BlockingQueue

博客介绍了 BlockingQueue 的数据生产消费规则,即若队列中有数据,需等数据消费后才能再生产,否则会阻塞,还提及了 SynchronousQueueDemo.java 及备注来自周老师。
摘要由CSDN通过智能技术生成

组赛队列,BlockingQueue 如果有数据,只能等数据消费以后再生产。否则阻塞。

SynchronousQueueDemo.java

public static void main(String[] args) {
    BlockingQueue blockingQueue = new SynchronousQueue();
    new Thread(() -> {
        try {
            System.out.println(Thread.currentThread().getName() + " put 1");
            blockingQueue.put("1");
            System.out.println(Thread.currentThread().getName() + " put 2");
            blockingQueue.put("2");
            System.out.println(Thread.currentThread().getName() + " put 3");
            blockingQueue.put("3");
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }, "aaa").start();

    new Thread(() -> {
        try {
            TimeUnit.SECONDS.sleep(3);
            System.out.println(Thread.currentThread().getName() + "  " +blockingQueue.take());
            TimeUnit.SECONDS.sleep(3);
            System.out.println(Thread.currentThread().getName() + "  " +blockingQueue.take());
            TimeUnit.SECONDS.sleep(3);
            System.out.println(Thread.currentThread().getName() + "  " +blockingQueue.take());
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }, "bbb").start();
}

结果:

aaa put 1
bbb  1
aaa put 2
bbb  2
aaa put 3
bbb  3

备注:来自周老师。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值