Java program output - concurrent
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.
can the output of this program ( the way it is) be zero?
Yes, that's possible. The code does not guarantee in any way that t1
will finish before t2
finishes. If that's your intent, you may find CountdownLatch
or CyclicBarrier
useful. Click the links, their javadocs contains code examples.
That said, I'd rather pass a reference of the AtomicInteger
as constructor argument of the both runnables instead of accessing it the static way.
With one small change you can guarantee that the output will be 1
:
public void run(){
int x = 1;
if(Test2.c.b.get() == 1)
x = Test2.c.a;
System.out.println("Value of x = "+x);
}
Because of the ordering guarantees of volatile reads/writes:
x
is initally1
- The only other value that can be assigned to
x
is the value ofTest2.c.a
Test2.c.a
can be copied tox
only if1
was previously read fromTest2.c.b
1
is written toTest2.c.b
only after writing1
toTest2.c.a
- Because
Test2.c.b
is volatile, any thread that reads it also observes all previous writes to all variables (volatile or not) by the same thread that wrote toTest2.c.b
. That meanst2
also sees the write of1
toTest2.c.a
- If the test fails (i.e. the read of
Test2.c.b
returns something other than1
) then x retains its initial value of1
, so the output is still1
.
I suspect this is what the author of this program was trying to illustrate, and the default value of 0
for x
was a typo.
精彩评论