ArrayBlockingQueue

/**
 *  add    超过capacity会抛出异常     remove  队列为空会抛出异常      add和remove底层也是调用的offer和poll方法
 *
 *  offer  超过capacity会返回false    poll   队列为空会返回null
 *
 *  put    超过capacity会阻塞         take 队列为空会阻塞
 *
 */
public class ArrayBlockingQueueTest {

    static ArrayBlockingQueue<String> queue = new ArrayBlockingQueue(2);

    public static void main(String[] args) throws InterruptedException {
//        testAdd();
//        testRemove();

//        testOffer();
//        testPoll();

//        testPut();
//        testTake();

    }


    /**
     * 超过capacity会抛出异常
     */
    public static void testAdd() {
        queue.add("hello1");
        queue.add("hello2");
        queue.add("hello3");
    }

    /**
     * 队列为空抛出异常
     */
    public static void testRemove() {
        queue.remove();

    }

    /**
     * 超过capacity会返回false
     */
    public static void testOffer() {
        queue.offer("hello1");
        queue.offer("hello2");
        System.out.println(queue.offer("hello3"));
    }

    /**
     * 队列为空返回null
     */
    public static void testPoll() {
        System.out.println(queue.poll());
    }

    /**
     * 超过capacity会阻塞
     */
    public static void testPut() throws InterruptedException {
        queue.put("hello1");
        queue.put("hello2");
        queue.put("hello3");
    }


    /**
     * 队列为空会阻塞
     */
    public static void testTake() throws InterruptedException {
        queue.take();

    }

}
原文地址:https://www.cnblogs.com/moris5013/p/12043687.html