Java 9中Thread.onSpinWait()方法的重要性是什么?
public static void onSpinWait()
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!"); } } }
输出
<strong>Done! Done!</strong>
以上就是Java 9中Thread.onSpinWait()方法的重要性是什么?的详细内容,更多请关注其它相关文章!