指令重排案例


package thread;

public class ResortDemo {
    static int i = 0;
    static boolean f = false;

    public static void main(String[] args) {

        new Thread(() -> {
            try {
                Thread.sleep(100);
                i++;
                f = true;
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }, String.valueOf("aaa")).start();
        new Thread(() -> {
            while (!f) {
                System.out.println(i);
            }

        }, String.valueOf("bbb")).start();


    }


}

由于i和flag没有依赖顺序,可能发生指令重排,在bbb线程执行时,aaa线程中的i++和f=true顺序可能发生改变,理想中是i先加1,bbb线程输出最后一个1以后退出,但是如果先执行了f=true,就会全部输出0

相关