Java中的 ArrayBlockingQueue size() 方法
ArrayBlockingQueue是有界的阻塞队列,它在内部存储由数组支持的元素。
- ArrayBlockingQueue类是Java集合框架的成员。
- 有界意味着它将具有固定大小,您不能存储数量超过队列容量的元素。
- 队列还遵循 FIFO(先进先出)规则来存储和删除队列中的元素。
- 如果你试图将一个元素放入一个满队列或从一个空队列中取出一个元素,那么队列会阻止你。
size()方法返回队列包含的元素数量。通过计算队列容量和队列大小之间的差异,大小是查看队列包含多少元素以及可以向该队列添加多少元素的重要方法。
句法:
public int size()
参数:该方法不带任何参数。
返回值:该方法返回此队列中的元素个数。
下面的程序说明了 ArrayBlockingQueue 的 size() 方法。
方案一:
Java
// Program to Demonstrate the size() method
// of ArrayBlockingQueue.
import java.util.concurrent.ArrayBlockingQueue;
public class GFG {
public static void main(String[] args) {
// Define capacity of ArrayBlockingQueue
int capacity = 5;
// Create object of ArrayBlockingQueue
ArrayBlockingQueue queue = new
ArrayBlockingQueue(capacity);
// Add elements to ArrayBlockingQueue
queue.add(23);
queue.add(32);
queue.add(45);
// Print size of queue after adding numbers
int size=queue.size();
System.out.println("After adding numbers"+
" Queue size = " +size);
// Add more elements to ArrayBlockingQueue
queue.add(88);
queue.add(42);
// Print size of queue after adding numbers
size=queue.size();
System.out.println("After adding more numbers"
+" Queue size = " +size);
}
}
Java
// Program to demonstrate size() method of
// ArrayBlockingQueue.
import java.util.concurrent.ArrayBlockingQueue;
public class GFG {
public static void main(String[] args) {
// Define capacity of ArrayBlockingQueue
int capacity = 5;
// Create object to store 5 names
ArrayBlockingQueue names = new
ArrayBlockingQueue(capacity);
// Add element to ArrayBlockingQueue
names.add("Aman");
names.add("Siddhant");
// Print size of queue after adding numbers
int size = names.size();
System.out.println("After adding numbers"+
" Queue size = "+size);
// Add more elements to ArrayBlockingQueue
names.add("Raunak");
names.add("Suvo");
// Print size of queue after adding numbers
size=names.size();
System.out.println("After adding more numbers"+
" Queue size = "+size);
}
}
方案二:
Java
// Program to demonstrate size() method of
// ArrayBlockingQueue.
import java.util.concurrent.ArrayBlockingQueue;
public class GFG {
public static void main(String[] args) {
// Define capacity of ArrayBlockingQueue
int capacity = 5;
// Create object to store 5 names
ArrayBlockingQueue names = new
ArrayBlockingQueue(capacity);
// Add element to ArrayBlockingQueue
names.add("Aman");
names.add("Siddhant");
// Print size of queue after adding numbers
int size = names.size();
System.out.println("After adding numbers"+
" Queue size = "+size);
// Add more elements to ArrayBlockingQueue
names.add("Raunak");
names.add("Suvo");
// Print size of queue after adding numbers
size=names.size();
System.out.println("After adding more numbers"+
" Queue size = "+size);
}
}
参考: https: Java/util/concurrent/ArrayBlockingQueue.html#size()