Home > Java > javaTutorial > body text

What is the importance of Thread.onSpinWait() method in Java 9?

王林
Release: 2023-08-21 09:25:14
forward
997 people have browsed it

Java 9中Thread.onSpinWait()方法的重要性是什么?

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

Syntax

<strong>public static void onSpinWait()</strong>
Copy after login

Example

is:

Example

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!");
      }
   }
}
Copy after login

Output

<strong>Done!
Done!</strong>
Copy after login

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!

source:tutorialspoint.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template