This may be a stupid question, but can the output of this program (as it is) be zero?
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);
}
}
The reason I'm asking about this is because although I use AtomicInteger, the if () statement in MyTest2 can be executed first and then x will be null. straight?
or I don’t think directly.
Any help would be greatly appreciated.
source
share