← 中文资源

简体中文版本

OnSpinWait 自旋提示

在有界自旋循环里调用 Thread.onSpinWait,提示 CPU 该线程只是在等待标志位而不是执行计算,避免空转消耗调度资源。

阅读英文原文

实现说明

OnSpinWait 自旋提示的核心是类 Main。 while (!ready.get() && spins < 100_000_000) 反复执行,循环体之外没有别的重复。

使用要点

  • 跑完文件,输出里会留下标记——observed ready:、spin rounds:、spin hint finished。

常见问题

运行「OnSpinWait 自旋提示」会打印什么?

不用做任何设置,直接把文件跑完——输出里的 observed ready:、spin rounds:、spin hint finished 标签标明各步骤。

核心语句

Thread.onSpinWait();
Thread.sleep(20);

代码示例

import java.util.concurrent.atomic.AtomicBoolean;

public class Main {
    public static void main(String[] args) throws InterruptedException {
        AtomicBoolean ready = new AtomicBoolean(false);

        Thread worker = new Thread(() -> {
            int spins = 0;
            // onSpinWait hints that this thread is waiting, not computing
            while (!ready.get() && spins < 100_000_000) {
                Thread.onSpinWait();
                spins++;
            }
            System.out.println("observed ready: " + ready.get());
            System.out.println("spin rounds: " + spins);
        });

        worker.start();
        Thread.sleep(20);
        ready.set(true);
        worker.join();
        System.out.println("spin hint finished");
    }
}