Simplest and understandable example of volatile keyword in Java

后端 未结 12 873
梦谈多话
梦谈多话 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:43

    I have modified your example slightly. Now use the example with keepRunning as volatile and non volatile member :

    class TestVolatile extends Thread{
        //volatile
        boolean keepRunning = true;
    
        public void run() {
            long count=0;
            while (keepRunning) {
                count++;
            }
    
            System.out.println("Thread terminated." + count);
        }
    
        public static void main(String[] args) throws InterruptedException {
            TestVolatile t = new TestVolatile();
            t.start();
            Thread.sleep(1000);
            System.out.println("after sleeping in main");
            t.keepRunning = false;
            t.join();
            System.out.println("keepRunning set to " + t.keepRunning);
        }
    }
    

提交回复
热议问题