Java volatile variable does not behave correctly.

public class MyThread
{
    volatile static int i;

    public static class myT extends Thread
    {
        public void run ()
        {
            int j = 0;
            while(j<1000000){
                i++;
                j++;
            }
        }
    }

    public static void main (String[] argv)
    throws InterruptedException{
            i = 0;

            Thread my1 = new myT();
            Thread my2 = new myT();
            my1.start();
            my2.start();

            my1.join();
            my2.join();

            System.out.println("i = "+i);
    }
}

Since volatile assemblies occur before the relationship, the final value of i must be strictly 2,000,000. However, the actual result is no different from the fact that it is not mutable for variable i. Can someone explain why he is not working here? Since I was declared volatile, it should be protected from memory mismatch.

+5
source share
1 answer

Can someone explain why he is not working here? Since I was declared volatile, it should be protected from memory mismatch.

, , , i++ . //. volatile . :

  • # 1 i, 10
  • , # 2 i, 10
  • # 1 i 11
  • # 2 i 11
  • thread # 1 11 i
  • thread # 2 11 i

, , 2 , , , 1. . . : volatile int Java?

, , - AtomicInteger, .

static final AtomicInteger i = new AtomicInteger(0);
...
        for (int j = 0; j<1000000; j++) {
            i.incrementAndGet();
        }
+8

All Articles