Thread.onSpinWait()方法在Java 9中引入。它是Thread類別的一個靜態方法,可以選擇性地在忙等待循環中呼叫。它允許JVM在某些系統架構上發出處理器指令,以改善這種自旋等待循環的回應時間,並減少核心執行緒的功耗。它可以改善java程式的整體功耗,並允許其他核心執行緒以相同的功耗範圍內更快地執行。
<strong>public static void onSpinWait()</strong>
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 <strong>abstract </strong>static class Task implements Runnable { volatile boolean canStart; void start() { this.canStart = true; } } private <strong>static </strong>class NormalTask extends Task { <strong>@Override</strong> public void run() { while(!this.canStart) { } System.out.println("Done!"); } } private <strong>static </strong>class SpinWaitTask extends Task { <strong>@Override</strong> public void run() { while(!this.canStart) { Thread.<strong>onSpinWait()</strong>; } System.out.println("Done!"); } } }
<strong>Done! Done!</strong>
以上是Java 9中Thread.onSpinWait()方法的重要性是什麼?的詳細內容。更多資訊請關注PHP中文網其他相關文章!