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

后端 未结 6 1121
别跟我提以往
别跟我提以往 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:24

    To expand on the answer from @jed-wesley-smith, if you drop this into a new project, take out the volatile keyword from the iterationCount, and run it, it will never stop. Adding the volatile keyword to either str or iterationCount would cause the code to end successfully. I've also noticed that the sleep can't be smaller than 5, using Java 8, but perhaps your mileage may vary with other JVMs / Java versions.

    public static class DelayWrite implements Runnable
    {
        private String str;
        public volatile int iterationCount = 0;
    
        void setStr(String str)
        {
            this.str = str;
        }
    
        public void run()
        {
            while (str == null)
            {
                iterationCount++;
            }
            System.out.println(str + " after " + iterationCount + " iterations.");
        }
    }
    
    public static void main(String[] args) throws InterruptedException
    {
        System.out.println("This should print 'Hello world!' and exit if str or iterationCount is volatile.");
        DelayWrite delay = new DelayWrite();
        new Thread(delay).start();
        Thread.sleep(5);
        System.out.println("Thread sleep gave the thread " + delay.iterationCount + " iterations.");
        delay.setStr("Hello world!!");
    }
    

提交回复
热议问题