这可能是一个愚蠢的问题,但是这个程序的输出(它的方式)可以为零吗?
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 的值为零..对吗?
还是我思维不清晰。
如有任何帮助,我们将不胜感激。
最佳答案
can the output of this program ( the way it is) be zero?
是的,这是可能的。代码不以任何方式保证 t1
将在 t2
完成之前完成。如果这是你的意图,你可能会发现 CountdownLatch
或 CyclicBarrier
有用。单击链接,它们的 javadoc 包含代码示例。
也就是说,我宁愿将 AtomicInteger
的引用作为两个可运行对象的构造函数参数传递,而不是以静态方式访问它。
关于Java程序输出——并发,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3483220/