import java.util.UUID;
import java.util.concurrent.ArrayBlockingQueue;
public class ArrayBlockingQueueTest2 {
public static void main(String[] args) {
try {
ArrayBlockingQueue<String> arrayBlockingQueue = new ArrayBlockingQueue<String>(10);
new Thread(){
public void run(){
try {
while (true){
String msg = Thread.currentThread().getName()+"-->"+ UUID.randomUUID().toString();
boolean result = false;
// add 如多队列满了,再放入就会报错
result = arrayBlockingQueue.add(msg);
System.out.println(result+" --> add放入一个对象后的数量:"+arrayBlockingQueue.size());
msg = Thread.currentThread().getName()+"-->"+ UUID.randomUUID().toString();
// put 如多队列满了,再放入就会阻塞,直到队列可以放入时在解除阻塞
arrayBlockingQueue.put(msg);
System.out.println("put放入一个对象后的数量:"+arrayBlockingQueue.size());
msg = Thread.currentThread().getName()+"-->"+ UUID.randomUUID().toString();
// offer 如多队列满了,再放入不报错也不阻塞,返回false
result = arrayBlockingQueue.offer(msg);
System.out.println(result+" --> offer放入一个对象后的数量:"+arrayBlockingQueue.size());
String d = null;
Thread.sleep(1000);
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}.start();
new Thread(){
@Override
public void run() {
String threadName = Thread.currentThread().getName();
while (true){
try {
//仅仅拿出来进行窥探,并不实际把数据从队列中移除
String msg = arrayBlockingQueue.peek();
System.out.println(threadName+" : peek拿出的数据为:"+msg+" ------> 拿出一个数据后,数量是 "+arrayBlockingQueue.size());
// take 如果数量是0的时候,进行阻塞
msg = arrayBlockingQueue.take();
System.out.println(threadName+" : take拿出的数据为:"+msg+" ------> 拿出一个数据后,数量是 "+arrayBlockingQueue.size());
// 从队列中拿出并进行移除,元素为0是不阻塞
msg = arrayBlockingQueue.poll();
System.out.println(threadName+" : poll拿出的数据为:"+msg+" ------> 拿出一个数据后,数量是 "+arrayBlockingQueue.size());
String d = null;
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}.start();
}catch (Exception e){
e.printStackTrace();
}
}
}
ArrayBlockingQueue
于 2022-02-03 22:11:42 首次发布