Java =》 Understanding of volatile

volatile is a lightweight synchronization mechanism provided by the Java virtual machine

  • Ensure visibility
  • Does not guarantee atomicity
  • Prohibition of instruction rearrangement

JMM

  • Visibility
  • Atomicity
  • Ordering
    the computer programs are executed, in order to improve performance, the compiler and processor instruction rearrangement often do, generally divided into the following 3

    results single-threaded environment to ensure that the final execution result of the program and the sequence of code consistency
    processor When reordering, the data dependency between instructions must be considered
/*
 * 可见性和原子性的实例代码
 * */

import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;

class MyData {
    // volatile int number = 0;
    volatile int number = 0;

    /*public void addNumber() {
        this.number = 60;
    }*/
    /*public synchronized void addNumber() {
        this.number = 60;
    }*/

    public void addself() {
        this.number++;
    }

    // AtomicInteger atomicInteger = new AtomicInteger();
    AtomicInteger atomicInteger = new AtomicInteger();

    public void atomicAddSelf() {
        atomicInteger.getAndIncrement();
    }

}

public class DemoVolatile {
    public static void main(String[] args) {
        // VisibilityVerificationVolatileDemo();
        AtomicityVerificationVolatileDemo();
    }

    private static void AtomicityVerificationVolatileDemo() {
        // 原子性验证
        // 定义1000个线程,调用addSelf,查看最终结果,如果结果一致则表示原子性可以保证
        MyData mydata = new MyData();

        for (int i = 0; i < 20; i++) {
            new Thread(() -> {
                // 操作数据
                for (int j = 0; j < 1000; j++) {
                    mydata.addself();
                    mydata.atomicAddSelf();
                }
            }, String.valueOf(i)).start();
        }
        while (Thread.activeCount() > 2) {
            Thread.yield();
        }
        System.out.println("number ######### " + mydata.number);
        System.out.println("atomicInteger ######### " + mydata.atomicInteger);
    }

    private static void VisibilityVerificationVolatileDemo() {
        // 验证可见性
        MyData myData = new MyData();
        new Thread(() -> {
            System.out.println(Thread.currentThread().getName() + " start \t");
            try {
                TimeUnit.SECONDS.sleep(3);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            myData.addself();
            System.out.println(Thread.currentThread().getName() + " update valus = " + myData.number);
        }, "AAA").start();

        while (myData.number == 0) {

        }
        System.out.println(Thread.currentThread().getName() + " is over ");
    }

}



Guess you like

Origin www.cnblogs.com/cerofang/p/12684412.html