volatile关键字的测试

来源:互联网 发布:mac备份 编辑:程序博客网 时间:2024/06/05 04:13
public class VolatileTest {volatileint  x = 1;Executor executor = Executors.newFixedThreadPool(4);public static void main(String[] args) {new VolatileTest().run();}void run(){executor.execute(new T1());executor.execute(new T2());}class T1 implements Runnable{public void run() {int s = 0;for(;;){if(x>0x0fffffff){break;}s= x;if(x==0&&s>0){System.out.println(s);}x++;}System.out.println("end");}}class T2 implements Runnable{public void run(){for(;;){x = 0;try {Thread.sleep(1);} catch (InterruptedException e) {// TODO Auto-generated catch blocke.printStackTrace();}}}}}

输出结果:

129263
129875
109012
78212
129456
202969
147509
257724
85193
107776
129820
251508
130972
75328

将变量x volatile去掉 

直接输出

end