Java 9中引入了Thread.onSpinWait()方法。它是Thread类的静态方法,可以选择在繁忙的等待循环中调用。它允许JVM在某些系统体系结构上发布处理器指令,以改善此类自旋等待循环中的响应时间,并减少核心线程的功耗。它可以提高Java程序的总体功耗,并允许其他核心线程在相同的功耗范围内以更快的速度执行。
public static void onSpinWait()
public class ThreadOnSpinWaitTest { public static void main(final String args[]) throws InterruptedException { final NormalTask task1 = new NormalTask(); final SpinWaitTask task2 = new SpinWaitTask(); final Thread thread1 = new Thread(task1); thread1.start(); final Thread thread2 = new Thread(task2); thread2.start(); new Thread(() -> { try { Thread.sleep(1000); } catch(final InterruptedException e) { e.printStackTrace(); } finally { task1.start(); task2.sta*rt(); } }).start(); thread1.join(); thread2.join(); } private abstract static class Task implements Runnable { volatile boolean canStart; void start() { this.canStart = true; } } private static class NormalTask extends Task { @Override public void run() { while(!this.canStart) { } System.out.println("Done!"); } } private static class SpinWaitTask extends Task { @Override public void run() { while(!this.canStart) { Thread.onSpinWait(); } System.out.println("Done!"); } } }
输出结果
Done! Done!