Java线程队列的使用-ConcurrentLinkedQueue

ConcurrentLinkedQueue是一个基于链表的非阻塞队列,利用CAS算法保证线程安全,提供高性能的并发操作。这个无界FIFO队列适合于多线程环境下的任务调度,示例代码展示了如何创建并使用ConcurrentLinkedQueue在三个线程间共享和执行任务。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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

可以看到,三个线程并发地从队列中获取任务并执行,没有出现数据的丢失或混乱。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值