Java ArrayBlockingQueue put() 方法

2025年1月7日 | 阅读 2 分钟

ArrayBlockingQueue 的 put() 方法将指定的元素添加到此队列的尾部。如果队列已满,它会等到有可用空间时再添加。

语法

参数

e - 这是要添加的元素。

指定者:

ArrayBlockingQueue 类的 put() 方法由 BlockingQueue 接口中的 put() 方法指定。.

抛出

put() 方法会抛出

  1. NullPointerException - 如果定义的元素为 null。
  2. InterruptedException - 如果方法在等待时被中断。

示例 1

输出

Elements in queue : [67, 109, 76, 876, 2]

示例 2

输出

Error:(9, 18) java: unreported exception java.lang.InterruptedException; must be caught or declared to be thrown
Error:(10, 18) java: unreported exception java.lang.InterruptedException; must be caught or declared to be thrown
Error:(11, 18) java: unreported exception java.lang.InterruptedException; must be caught or declared to be thrown
Error:(12, 18) java: unreported exception java.lang.InterruptedException; must be caught or declared to be thrown

我们应该将异常添加到方法签名中,或者将 put() 方法用 try-catch 块包围起来,否则会产生上述错误。

示例 3

输出

Exception in thread "main" java.lang.NullPointerException
	at java.util.concurrent.ArrayBlockingQueue.checkNotNull(ArrayBlockingQueue.java:150)
	at java.util.concurrent.ArrayBlockingQueue.put(ArrayBlockingQueue.java:348)
	at com.javaTpoint.ArrayBlockingQueuePutExample2.main(ArrayBlockingQueuePutExample2.java:13)

如果指定的元素为 null,则会如上所示产生 NullPointerException。