Home >Java >javaTutorial >What is the importance of Thread.onSpinWait() method in Java 9?
Thread.onSpinWait() method was introduced in Java 9. It is a static method of the Thread class that can be optionally called in a busy wait loop. It allows the JVM to issue processor instructions on certain system architectures to improve the response time of such spin wait loops and reduce core thread power consumption. It can improve the overall power consumption of java programs and allow other core threads to execute faster within the same power consumption range. The Chinese translation of
<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>
The above is the detailed content of What is the importance of Thread.onSpinWait() method in Java 9?. For more information, please follow other related articles on the PHP Chinese website!