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中文网其他相关文章!