← 中文资源

简体中文版本

SynchronousQueue 直接交接

SynchronousQueue 没有容量:put 必须等到另一线程恰好 take 才返回,数据不落任何缓冲,直接在提交线程与工作线程之间形成阻塞式会合。

阅读英文原文

实现说明

逻辑集中在类 JobHandoff里。 驱动整个流程的是 while (true) 这一个循环。

使用要点

  • 演示输出是带标签的(worker picked up:、worker interrupted, exiting、submitting:),每个操作都会留下自己的一行标注。

常见问题

运行「SynchronousQueue 直接交接」会打印什么?

整个文件跑完,输出行以 worker picked up:、worker interrupted, exiting、submitting: 这类前缀开头。

核心语句

Thread worker = new Thread(() -> {
    try {
        while (true) {
            String job = handoff.take();
            System.out.println("worker picked up: " + job);
        }
    } catch (InterruptedException stopped) {
        System.out.println("worker interrupted, exiting");
    }
});

代码示例

import java.util.concurrent.SynchronousQueue;

public class JobHandoff {

    public static void main(String[] args) throws InterruptedException {
        // 零容量队列:任何 put 都必须等到另一线程恰好 take,中间不缓冲
        SynchronousQueue<String> handoff = new SynchronousQueue<>();

        Thread worker = new Thread(() -> {
            try {
                while (true) {
                    String job = handoff.take();
                    System.out.println("worker picked up: " + job);
                }
            } catch (InterruptedException stopped) {
                System.out.println("worker interrupted, exiting");
            }
        });
        worker.start();

        for (String job : new String[] {"reindex-a", "reindex-b"}) {
            System.out.println("submitting: " + job);
            handoff.put(job); // 阻塞到 worker take 才返回
            System.out.println("confirmed handoff: " + job);
        }

        worker.interrupt();
        worker.join();
        System.out.println("worker finished: " + !worker.isAlive());
    }
}