package ifeve;import java.util.concurrent.atomic.AtomicInteger;/*** @Description* @Author msli* @Date 2021年10月13日*/public class InstructionReorderTest {private static int x = 0, y = 0;private static int a = 0, b = 0;private static boolean flag = true;public static void main(String[] args) throws InterruptedException {Method1();Method2();}private static void Method1() throws InterruptedException {int i = 0;for (;;) {i++;x = 0;y = 0;a = 0;b = 0;final Thread thread1 = new Thread(() -> {a = 1;x = b;});final Thread thread2 = new Thread(() -> {b = 2;y = a;});thread1.start();thread2.start();thread1.join();thread2.join();if (x==0 && y==0) {System.out.println("第"+i+"次调用 x==y==0");break;}}}public static void Method2() throws InterruptedException {int i = 0;while (true) {i++;a = 0;flag = false;Thread t1 = new Thread() {@Overridepublic void run() {a = 1;flag = true;}};int finalI = i;Thread t2 = new Thread() {@Overridepublic void run() {if (flag){if (a==0){System.out.format( "-----第%d次 发生指令重排序----- a = %d", finalI, a);}}}};t1.start();t2.start();t1.join();t2.join();}}}
此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。
如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。