using volatile keyword

后端 未结 6 1576
轮回少年
轮回少年 2020-12-21 02:26

As i understand, if we declare a variable as volatile, then it will not be stored in the local cache. Whenever thread are updating the values, it is updated to the main mem

6条回答
  •  悲&欢浪女
    2020-12-21 02:35

    Here is an example showing a variable that is accessed by two threads. The StarterThread thread sets the variable started when the thread starts. The WaiterThread waits for the variable started to be set.

    public class Main
    {
        static /*volatile*/ boolean started = false;
    
        private static class StarterThread extends Thread
        {
            public void run()
            {
                started = true;
            }
        }
    
        private static class WaiterThread extends Thread
        {
            public void run()
            {
                while (!started)
                {
                }
            }
        }
    
        public static void main(String[] args)
        {
            new StarterThread().start();
            new WaiterThread().start();
        }
    }
    

    If started is not volatile, then there is no synchronization point that guarantees that WaiterThread will ever get the updated value of the started variable. Consequently, the WaiterThread thread could potentially run "indefinitely".

提交回复
热议问题