Java 9 中 Thread.onSpinWait() 方法的重要性?
Thread.onSpinWait() 方法已在 Java 9 中引入。它是 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!"); } } }
Learn Java in-depth with real-world projects through our Java certification course. Enroll and become a certified expert to boost your career.
输出
Done! Done!
广告