volatile visibility and prohibition instruction reordering

Disclaimer: This article is a blogger original article, shall not be reproduced without the bloggers allowed. https://blog.csdn.net/u013219624/article/details/89235221

1. Visibility (modified to be volatile variable values ​​change, visible to other threads)

public static void main(String[] args) {
        MyThread myThread = new MyThread();
        myThread.start();
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        myThread.setFlag(false);
    }


    static class MyThread extends Thread {
        volatile boolean flag = true;

        @Override
        public void run() {
            while (flag) {
                System.out.println(Thread.currentThread().getName() + " running.");
                try {
                    Thread.sleep(500);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }

        public void setFlag(boolean flag) {
            System.out.println(Thread.currentThread().getName() + " change flag.");
            this.flag = flag;
        }
    }

2. prohibition instruction reordering

The following example is not modified flag volatile, so (configInfo = "change"; flag = false;) instruction sequence may be the first flag value is changed, problems occur so that the program

static boolean flag = true;
static String configInfo = "origin";

public static void main(String[] args) throws Exception {
    Thread threadA = new Thread(() -> {
        configInfo = "change";
        flag = false;
    });

    Thread threadB = new Thread(() -> {
        while (flag) {
        }
        System.out.println(Thread.currentThread().getName() + " " + configInfo);
    });
    threadA.start();
    threadB.start();

    threadA.join();
    threadB.join();
}

Guess you like

Origin blog.csdn.net/u013219624/article/details/89235221
Recommended