feat: ArrayBlockingQueue使用

This commit is contained in:
Bunny 2025-01-20 21:22:17 +08:00
parent d5f197ce34
commit 3356cdc986
1 changed files with 43 additions and 0 deletions

View File

@ -1,4 +1,47 @@
package cn.bunny.atomic;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.TimeUnit;
public class AtomicExample05 {
public static void main(String[] args) throws InterruptedException {
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);
}
}