← 中文资源

简体中文版本

ConcurrentLinkedQueue 无阻塞交接

无锁队列在多线程之间交接任务:offer 永不阻塞、poll 取空时返回 null 而非挂起线程;size() 是 O(n) 的弱一致估计,并发场景判空要用 isEmpty()。

阅读英文原文

实现说明

全部逻辑都在类 JobHandoff中。 循环只出现在 for (int i = 0; i < 3; i++),它的每次迭代处理一个元素。

使用要点

  • 演示输出是带标签的(polled:、rest:、empty:),每个操作都会留下自己的一行标注。

常见问题

运行「ConcurrentLinkedQueue 无阻塞交接」会打印什么?

不用做任何设置,直接把文件跑完——输出里的 polled:、rest:、empty: 标签标明各步骤。

核心语句

Thread producer = new Thread(() -> {
    for (int i = 0; i < 3; i++) {
        queue.offer("task-" + i);
    }
});

代码示例

import java.util.concurrent.ConcurrentLinkedQueue;

public class JobHandoff {

    public static void main(String[] args) throws InterruptedException {
        // 无锁(lock-free)handoff 队列:offer 永不阻塞,也没有容量上限
        ConcurrentLinkedQueue<String> queue = new ConcurrentLinkedQueue<>();

        Thread producer = new Thread(() -> {
            for (int i = 0; i < 3; i++) {
                queue.offer("task-" + i);
            }
        });
        producer.start();
        producer.join(); // join 之后主线程才能安全消费全部任务

        // poll 取走队首;取不到时返回 null 而不是挂起当前线程
        System.out.println("polled: " + queue.poll());
        System.out.println("rest:   " + queue);

        // size() 要遍历整条链表且是弱一致估计:并发判空一律用 isEmpty()
        System.out.println("empty: " + queue.isEmpty() + " size: " + queue.size());
    }
}