Queue 阻塞队列 LinkedBlockingQueue

  

  与ArrayBlockingQueue 除了数据存储的结构不同、大小可以不指定之外,其他的都一致 

package com.dh.learn.queue;

import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;

public class LearnLinkedBlockingQueue {
    // 底层是链表实现的
    // 阻塞方式的实现与ArrayBlockingQueue一致:
    //      ReenTrantLock 保证线程安全
    //      Condition的await() single() 保证队列阻塞
    public static void main(String[] args) throws InterruptedException {
        // 可指定链表大小,不指定时默认是Integer.MAX_VALUE (2的31次方-1)
        BlockingQueue<String> linkedBlockingQueue = new LinkedBlockingQueue<>(2);
        linkedBlockingQueue.put("aaaa");
        linkedBlockingQueue.put("bbbb");

        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    System.out.println("取值,使队列不满");
                    linkedBlockingQueue.take();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }).start();
        linkedBlockingQueue.put("cccc");

        System.out.println(linkedBlockingQueue.toString());
    }
}

猜你喜欢

转载自www.cnblogs.com/han6/p/11275187.html