Simplest and understandable example of volatile keyword in Java

后端 未结 12 853
梦谈多话
梦谈多话 2020-11-28 19:43

I\'m reading about volatile keyword in Java and completely understand the theory part of it.

But, what I\'m searching for is, a good case example, which sho

12条回答
  •  借酒劲吻你
    2020-11-28 20:30

    Please find the solution below,

    The value of this variable will never be cached thread-locally: all reads and writes will go straight to "main memory". The volatile force the thread to update the original variable for each time.

    public class VolatileDemo {
    
        private static volatile int MY_INT = 0;
    
        public static void main(String[] args) {
    
            ChangeMaker changeMaker = new ChangeMaker();
            changeMaker.start();
    
            ChangeListener changeListener = new ChangeListener();
            changeListener.start();
    
        }
    
        static class ChangeMaker extends Thread {
    
            @Override
            public void run() {
                while (MY_INT < 5){
                    System.out.println("Incrementing MY_INT "+ ++MY_INT);
                    try{
                        Thread.sleep(1000);
                    }catch(InterruptedException exception) {
                        exception.printStackTrace();
                    }
                }
            }
        }
    
        static class ChangeListener extends Thread {
    
            int local_value = MY_INT;
    
            @Override
            public void run() {
                while ( MY_INT < 5){
                    if( local_value!= MY_INT){
                        System.out.println("Got Change for MY_INT "+ MY_INT);
                        local_value = MY_INT;
                    }
                }
            }
        }
    
    }
    

    Please refer this link http://java.dzone.com/articles/java-volatile-keyword-0 to get more clarity in it.

提交回复
热议问题