Home  >  Article  >  Java  >  Analysis of exception examples thrown by java queue

Analysis of exception examples thrown by java queue

WBOY
WBOYforward
2023-05-19 11:13:05870browse

1. When the queue is full and the element is inserted into the queue again, an IllegalStateException (QueueFull) exception will be thrown.

2. If the queue is empty, extracting an element from the queue will cause a NoSuchElementException exception.

Example

public class MyBlockQueue {
    public static void main(String[] args) {
        ArrayBlockingQueue<Integer> q = new ArrayBlockingQueue<Integer>(3);
        new Thread(()->{
            q.add(1);
            System.out.println(Thread.currentThread().getName()+"放入一个元素");
            q.add(2);
            System.out.println(Thread.currentThread().getName()+"放入一个元素");
            q.add(3);
            System.out.println(Thread.currentThread().getName()+"放入一个元素");
        },"线程1").start();
 
        new Thread(()->{
            q.remove();
            System.out.println(Thread.currentThread().getName()+"拿走一个元素");
            q.remove();
            System.out.println(Thread.currentThread().getName()+"拿走一个元素");
            q.remove();
            System.out.println(Thread.currentThread().getName()+"拿走一个元素");
            q.remove();
            System.out.println(Thread.currentThread().getName()+"拿走一个元素");
        },"线程2").start();
    }
}

The above is the detailed content of Analysis of exception examples thrown by java queue. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:yisu.com. If there is any infringement, please contact admin@php.cn delete