Created
June 18, 2014 11:05
-
-
Save wangzaixiang/5d9866bdd0688ca084b2 to your computer and use it in GitHub Desktop.
Just for test the anti-volatile example, see http://ifeve.com/java-memory-model-1/
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package volatile_demo; | |
import java.util.concurrent.BrokenBarrierException; | |
import java.util.concurrent.CyclicBarrier; | |
public class Test2 { | |
int a = 0; | |
int b = 0; | |
int x = -1; | |
int y = -1; | |
public void path1(){ | |
a = 1; | |
x = b; | |
} | |
public void path2(){ | |
b = 2; | |
y = a; | |
} | |
public boolean test() throws InterruptedException { | |
a = b = 0; | |
x = y = -1; | |
CyclicBarrier barrier = new CyclicBarrier(2); | |
Thread t1 = new Thread(){ | |
public void run() { | |
try { | |
barrier.await(); | |
path1(); | |
} catch (InterruptedException | BrokenBarrierException e) { | |
} | |
}; | |
}; | |
Thread t2 = new Thread(){ | |
public void run() { | |
try { | |
barrier.await(); | |
path2(); | |
} catch (InterruptedException | BrokenBarrierException e) { | |
} | |
}; | |
}; | |
t1.start(); | |
t2.start(); | |
t1.join(); | |
t2.join(); | |
if(x == 0 && y == 0) | |
return false; | |
else return true; | |
} | |
public static void main(String[] args) throws InterruptedException { | |
for(int i = 0; i< 100*1000; i++){ | |
if(new Test2().test()==false) { | |
System.out.println("found on " + i); | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment