ConcurrentLinkedQueue是一种基于链表的非阻塞队列,它使用CAS算法来保证线程安全,性能比阻塞队列高。它是一个无界队列,可以无限制地向队列中添加元素。它是一个FIFO(先进先出)的队列,即先添加的元素先被获取。
ConcurrentLinkedQueue可以用于实现高并发的场景,例如多个线程共享一个任务队列。例如,下面的代码创建了一个ConcurrentLinkedQueue,并向其中添加了10个任务。然后创建了三个线程,从队列中获取任务并执行。
import java.util.concurrent.ConcurrentLinkedQueue;
// 定义一个任务类
class Task {
// 任务名称
private String name;
// 构造方法,传入任务名称
public Task(String name) {
this.name = name;
}
// 执行任务的方法
public void execute() {
System.out.println(Thread.currentThread().getName() + " is executing task: " + name);
}
}
public class ConcurrentLinkedQueueDemo {
public static void main(String[] args) {
// 创建一个并发链表队列
ConcurrentLinkedQueue<Task> clq = new ConcurrentLinkedQueue<>();
// 向队列中添加10个任务
for (int i = 0; i < 10; i++) {
clq.offer(new Task("task" + i));
}
// 创建三个线程,从队列中获取任务并执行
for (int i = 0; i < 3; i++) {
new Thread(() -> {
while (!clq.isEmpty()) {
Task task = clq.poll();
if (task != null) {
task.execute();
}
}
}, "thread" + i).start();
}
}
}
输出结果(可能有不同):
thread0 is executing task: task0
thread1 is executing task: task1
thread2 is executing task: task2
thread0 is executing task: task3
thread1 is executing task: task4
thread2 is executing task: task5
thread0 is executing task: task6
thread1 is executing task: task7
thread2 is executing task: task8
thread0 is executing task: task9
可以看到,三个线程并发地从队列中获取任务并执行,没有出现数据的丢失或混乱。