The code example which can prove “volatile” declare should be used

后端 未结 6 1122
别跟我提以往
别跟我提以往 2020-12-15 07:48

Currently I can\'t understand when we should use volatile to declare variable.

I have do some study and searched some materials about it for a long time

6条回答
  •  再見小時候
    2020-12-15 08:09

    A minimalist example in java 8, if you remove volatile keyword it will never end.

    public class VolatileExample {
    
        private static volatile boolean BOOL = true;
    
        public static void main(String[] args) throws InterruptedException {
            new Thread(() -> { while (BOOL) { } }).start();
            TimeUnit.MILLISECONDS.sleep(500);
            BOOL = false;
        }
    }
    

提交回复
热议问题