指令重排序
Posted Rainyn
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了指令重排序相关的知识,希望对你有一定的参考价值。
@Slf4j public class SimpleHappenBefore { private static int a = 0; private static boolean flag = false; public static void main(String[] args) throws InterruptedException { for (int i = 0; i < 1000; i++) { ThreadA threadA = new ThreadA(); ThreadB threadB = new ThreadB(); threadA.start(); threadB.start(); threadA.join(); threadB.join(); a = 0; flag = false; } } static class ThreadA extends Thread { @Override public void run() { //这里的指令重排序
a = 1; flag = true; } } static class ThreadB extends Thread { @Override public void run() { if (flag) { a = a * 1; } if (a == 0) { System.out.println("ha,a==0"); } } } }
以上是关于指令重排序的主要内容,如果未能解决你的问题,请参考以下文章