How can “while (i == i) ;” be a non-infinite loop in a single threaded application?

前端 未结 12 1137
甜味超标
甜味超标 2020-12-04 09:41

I just got a question that I can\'t answer.

Suppose you have this loop definition in Java:

while (i == i) ;

What is the type of

12条回答
  •  一个人的身影
    2020-12-04 10:30

    i == i is not atomic. Proved by such program:

    static volatile boolean i = true;
    public static void main(String[] args) throws InterruptedException
    {
        new Thread() {
            @Override
            public void run() {
                while (true) {
                    i = !i;
                }
            }
        }.start();
    
        while (i == i) ;
        System.out.println("Not atomic! i: " + i);
    }
    

    Update Here is one more example of not-infinite loop (no new threads are created).

    public class NoNewThreads {
        public static void main(String[] args) {
            new NoNewThreads();
            System.gc();
            int i = 500;
            System.out.println("Still Running");
            while (i == i) ;
        }
    
        @Override
        protected void finalize() throws Throwable {
            super.finalize();
            Thread.sleep(1000);
            System.exit(0);
        }
    }
    

提交回复
热议问题