BlockingQueue

BlockingQueue requires that the thread be blocked when the queue is empty or full

way There is a return value, an exception is thrown Return value, no exception thrown No return value, blocking wait There is a return value, timeout wait
add add() offer() put() offer(..)
remove remove() poll() take() poll(..)
Detects the head element of the queue element() peek()
public static void main(String[] args) {
        // 3 indicates the capacity of the queue
        BlockingQueue<String> objects = new ArrayBlockingQueue<>(3);
        objects.add("a");
        objects.add("c");
        objects.add("b");
        //objects.add("d"); An error Queue full
        //System.out.println(objects.offer("d")); Output is false
        // objects.put("d"); Block waiting for
        //objects.offer("d",2, TimeUnit.SECONDS); 2 indicates the time, and TimeUtil.Seconds indicates the time unit
        System.out.println(objects.remove());
        System.out.println(objects.remove());
        System.out.println(objects.remove());
        //System.out.println(objects.remove()); / / error NoSuchElementException
        //System.out.println(objects.poll()); Output is null
        //objects.take(); Block waiting for
        //objects.poll(2,TimeUnit.SECONDS); Wait two seconds, abort over time
       

    }
Copy the code

SynchronousQueue SynchronousQueue

No capacity, put out must take.


public class BlockingQueueTest {
    public static void main(String[] args) {
        BlockingQueue<String > objects = new SynchronousQueue<>();

        new Thread(()->{

            try {
                System.out.println(Thread.currentThread().getName()+"put");
                objects.put(String.valueOf(1));
                System.out.println(Thread.currentThread().getName()+"put");
                objects.put(String.valueOf(2));
                System.out.println(Thread.currentThread().getName()+"put");
                objects.put(String.valueOf(2));

            } catch (InterruptedException e) {
                e.printStackTrace();
            }

        }).start();
        new Thread(()->{
            try {
                Thread.sleep(2);
                System.out.println(Thread.currentThread().getName()+"get"+objects.take());
                Thread.sleep(2);
                System.out.println(Thread.currentThread().getName()+"get"+objects.take());
                Thread.sleep(2);
                System.out.println(Thread.currentThread().getName()+"get"+objects.take());
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }).start();

    }

}
Thread-0put
Thread-1get1
Thread-0put
Thread-1get2
Thread-0put
Thread-1get2
Copy the code