feat: PriorityBlockingQueue 使用

This commit is contained in:
Bunny 2025-01-20 21:28:35 +08:00
parent 3356cdc986
commit e371543141
2 changed files with 57 additions and 0 deletions

View File

@ -0,0 +1,44 @@
# Java并发容器使用
## ArrayBlockingQueue使用
```java
ArrayBlockingQueue<String> queue = new ArrayBlockingQueue<>(8);
// 阻塞添加
queue.add("1");
queue.add("2");
queue.add("3");
System.out.println(queue);
// 非阻塞添加
queue.put("4");
queue.put("5");
System.out.println(queue);
// 阻塞添加,但队列满不会进入阻塞
queue.offer("6");
queue.offer("7");
System.out.println(queue);
// 指定时间内进入阻塞
queue.offer("8", 3, TimeUnit.SECONDS);
queue.offer("9", 3, TimeUnit.SECONDS);// 8个队列满不会进入阻塞
System.out.println(queue);
// 从头部获取数据并移出,如果队列为空进入阻塞直到有数据添加
String take = queue.take();
System.out.println(take);
// 获取数据并移出队列第一个元素如果队列为空将会阻塞指定的时间直到在此期间有新数据写入或者当前线程被其他线程中断当线程超时会返回null
String poll = queue.poll(3, TimeUnit.SECONDS);
System.out.println(poll);
// 从头部获取数据并移出,如果队列为空不会阻塞
String poll1 = queue.poll();
System.out.println(poll1);
// 从头部获取数据不会移除队列为空不会阻塞直接返回null
String peek = queue.peek();
System.out.println(peek);
```

View File

@ -1,4 +1,17 @@
package cn.bunny.atomic;
import java.util.concurrent.PriorityBlockingQueue;
public class AtomicExample06 {
public static void main(String[] args) {
// 无边界队列可以定义初始容量并不是最大容量
PriorityBlockingQueue<Integer> queue = new PriorityBlockingQueue<>(2);
System.out.println(queue);
// 队列的添加方法都等于offer方法
queue.offer(1);
queue.offer(10);
queue.offer(3);
System.out.println(queue);
}
}