【发布时间】:2011-03-29 20:00:30
【问题描述】:
这可能是一个愚蠢的问题,但是,这个程序的输出(它的方式)可以为零吗?
public class Test2{
int a = 0;
AtomicInteger b = new AtomicInteger();
public static Test2 c = new Test2();
public static void main(String[] args){
Thread t1 = new Thread(new MyTest1());
Thread t2 = new Thread (new Mytest2());
t1.start();
t2.start();
}
}
class MyTest1 implements Runnable{
public void run(){
Test2.c.a = 1;
Test2.c.b.compareAndSet(0,1);
}
}
class Mytest2 implements Runnable{
public void run(){
int x = 0;
if(Test2.c.b.get() == 1)
x = Test2.c.a;
System.out.println("Value of x = "+x);
}
}
我问这个的原因是,虽然我使用的是 AtomicInteger,但 MyTest2 中的 if() 语句可能会先执行,然后 x 的值将为零..对吗?
还是我的想法不正确。
任何帮助将不胜感激。
【问题讨论】:
标签: java concurrency