In-depth understanding of volatile keyword

For java, there is a keyword that is not well understood, and that is the volatile keyword.

public class VolatileDemo {

    private static volatile int INIT_VALUE = 0; //After use
// private static int INIT_VALUE = 0; // effect before use
    private static final int MAXINT = 5;

    public static void main(String[] args) {

        /**
         * define thread one
          */
        Thread tReader = new Thread(()->{
            int localint = INIT_VALUE;
            while(localint < MAXINT){
                if(localint != INIT_VALUE){
                    Optional.of(Thread.currentThread().getName() + " the value is " + localint).ifPresent(System.out::println);
                    localint = INIT_VALUE;
                }
                //Optional.of(Thread.currentThread().getName()+" values is "+ localint +" and " + INIT_VALUE).ifPresent(System.out::println);
            }
        },"thread-reader");
        tReader.start();

        Thread tWriter = new Thread(()->{
            int localint = 0;
            while(localint < MAXINT){
                try {
                    Thread.sleep(100L);
                } catch (InterruptedException e) {
                    e.printStackTrace ();
                }
                Optional.of(Thread.currentThread().getName() + " update the value " + (++localint)).ifPresent(System.out::println);
                INIT_VALUE = localint;
            }
        },"thread-writer");
        tWriter.start();

        System.out.println("the main thread is finished...");

    }

}

  before use:

After use:

Summarize:

1) Ensures the visibility of different threads operating on this variable, that is, a thread modifies the value of a variable, and the new value is immediately visible to other threads.

2) Instruction reordering is prohibited.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325128851&siteId=291194637