阅读背景:

java 内存模型 重排序例子

来源:互联网 
1.重排序 理解

重排序是指编译器和处理器为了优化程序性能而对指令序列进行重新排序的一种手段

package com.pgf.pool; import java.util.concurrent.BrokenBarrierException; import java.util.concurrent.CyclicBarrier; /* 作者:pgf 时间:2019年12月20日 描述:当m1 和 m2 发生重排序后,先执行x=b,y=a; 在执行a=1,b=1,最后x=0,y=0 */ public class JmmTest { private int a=0; private int b = 0; private int x = 1; private int y=1; public void m1(){ a=1; x=b; } public void m2(){ b=1; y=a; } public void test() throws Exception { CyclicBarrier cyc = new CyclicBarrier(2); Thread thread1 = new Thread(new Runnable() { @Override public void run() { try { cyc.await(); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (BrokenBarrierException e) { // TODO Auto-generated catch block e.printStackTrace(); } m1(); } },"A"); Thread thread2 = new Thread(new Runnable() { @Override public void run() { try { cyc.await(); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (BrokenBarrierException e) { // TODO Auto-generated catch block e.printStackTrace(); } m2(); } },"B"); thread1.start(); thread2.start(); thread1.join(); thread1.join(); if(x==0 && y==0){ System.out.println("重排序了。。。。"); } } public static void main(String[] args) throws Exception { for(int i=0;i<100000;i++){ JmmTest jmmTest = new JmmTest(); jmmTest.test(); } } } pa



你的当前访问异常,请进行认证后继续阅读剩余内容。

分享到: