package ca.six.demo.lib.thread._volatile;

public class WhyVolatileExist {
    int a = 1;
    int b = 2;

    public void change() {
        a = 3;
        b = a;
    }

    public void print() {
        if (a == 1 && b == 3) {
            // why this is happening?
            System.out.println("Thread[" + Thread.currentThread().getName() + "]Confused1 : a = 1, b = 3");
        } else if (a == 3 && b == 2) {
            // never happened. Why?
            System.out.println("Thread[" + Thread.currentThread().getName() + "]Confused2 : a = 1, b = 3");
        } else {
            System.out.println("Thread[" + Thread.currentThread().getName() + "] b=" + b + ";a=" + a);
        }
    }

    public static void main(String[] args) {
        // create many many threads
        while (true) {
            // create test every time, to make sure a is 1 and b is 2 again
            final WhyVolatileExist test = new WhyVolatileExist();

            // one thread for changing
            new Thread(new Runnable() {
                @Override
                public void run() {
                    try {
                        Thread.sleep(10);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    test.change();
                }
            }).start();

            // one thread for printing
            new Thread(new Runnable() {
                @Override
                public void run() {
                    try {
                        Thread.sleep(10);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    test.print();
                }
            }).start();

        }
    }
}
@@ -40,126 +40,291 @@
 e;%0A%0A
-public class WhyVolatileExist %7B%0A    int a = 1;%0A    int b = 2;%0A%0A    public void change() %7B%0A        a = 3;%0A        b = a
+import java.util.concurrent.atomic.AtomicInteger;%0A%0Apublic class WhyVolatileExist %7B%0A    volatile AtomicInteger a = new AtomicInteger(1);%0A    volatile AtomicInteger b = new AtomicInteger(2);%0A%0A    public void change() %7B%0A        a = new AtomicInteger(3);%0A        b = new AtomicInteger(3)
 ;%0A  
@@ -363,24 +363,30 @@
        if (a
+.get()
  == 1 && b =
@@ -379,24 +379,30 @@
 () == 1 && b
+.get()
  == 3) %7B%0A   
@@ -564,16 +564,22 @@
 se if (a
+.get()
  == 3 &&
@@ -580,16 +580,22 @@
 = 3 && b
+.get()
  == 2) %7B
@@ -756,16 +756,18 @@
  else %7B%0A
+//
         

volatile : still have a=1, b = 3