It might be a silly question but, can the output of this program ( the way 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 this is, although I’m using AtomicInteger, the if() statement in MyTest2 might be executed first and then x will have the value zero..right?
or am I not thinking straight.
Any help would be highly appreciated.
Yes, that’s possible. The code does not guarantee in any way that
t1will finish beforet2finishes. If that’s your intent, you may findCountdownLatchorCyclicBarrieruseful. Click the links, their javadocs contains code examples.That said, I’d rather pass a reference of the
AtomicIntegeras constructor argument of the both runnables instead of accessing it the static way.