java 死循环 while(true) vs for(;;)

    xiaoxiao2026-03-15  8

    今天在看AtomicInteger的乐观锁实现(CAS);读源码发现它的死循环式是这么写的

    /** * Atomically decrements by one the current value. * * @return the previous value */ public final int getAndDecrement() { for (;;) { int current = get(); int next = current - 1; if (compareAndSet(current, next)) return current; } }

    采用的是for(;;) 而我常用的习惯是用while(true),这两者有什么区别呢。是不是for(;;)要比while(true)快呢?

    做了如下测试

    /** * MainTest * * @author lilin * @date 16/12/1 */ public class MainTest { public static void main(String[] args) { forTest(); whileTest(); } public static void forTest(){ for(;;){ System.out.println("for"); } } public static void whileTest(){ while (true){ System.out.println("while"); } } }

    **编译 javac -p src/main/java/classes src/main/java/MainTest.java编译后的文件MainTest.class 代码如下**

    // // Source code recreated from a .class file by IntelliJ IDEA // (powered by Fernflower decompiler) // public class MainTest { public MainTest() { } public static void main(String[] var0) { forTest(); whileTest(); } public static void forTest() { while(true) { System.out.println("for"); } } public static void whileTest() { while(true) { System.out.println("while"); } } }

    发现最后都变成了while(true) 得出的结论他们最终的效果应该是一样的 。

    相关资源:cas java cas java 实例
    最新回复(0)