Jdk版本:jdk1.8.0_151
代码
1public class SimpleHappenBefore { 2 3 public static void main(String[] args) throws InterruptedException { 4 5 for(int i=0;i<500000;i++){ 6 SimpleHappenBefore.State state = new SimpleHappenBefore.State(); 7 ThreadA threadA=new ThreadA(state); 8 ThreadB threadB=new ThreadB(state); 9 threadA.start(); 10 threadB.start(); 11 12 threadA.join(); 13 threadB.join(); 14 } 15 } 16 17 static class ThreadA extends Thread{ 18 19 private final SimpleHappenBefore.State state; 20 21 ThreadA(SimpleHappenBefore.State state) { 22 this.state = state; 23 } 24 25 public void run(){ 26 state.a=1; 27 state.b=1; 28 state.c=1; 29 state.d=1; 30 } 31 } 32 33 static class ThreadB extends Thread{ 34 35 private final SimpleHappenBefore.State state; 36 37 ThreadB(SimpleHappenBefore.State state) { 38 this.state = state; 39 } 40 41 public void run(){ 42 if(state.b==1 && state.a==0){ 43 System.out.println("b=1"); 44 } 45 46 if(state.c==1 && (state.b==0 || state.a == 0)){ 47 System.out.println("c=1"); 48 } 49 50 if(state.d==1 && (state.a==0 || state.b==0 || state.c==0)){ 51 System.out.println("d==1"); 52 } 53 } 54 } 55 56 static class State { 57 public int a = 0; 58 public int b = 0; 59 public int c = 0; 60 public int d = 0; 61 } 62}
输出
1d==1 2d==1 3c=1