Home > Java > javaTutorial > body text

Analysis of exception examples thrown by java queue

WBOY
Release: 2023-05-19 11:13:05
forward
951 people have browsed it

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();
    }
}
Copy after login

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!

Related labels:
source:yisu.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template