Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 269
Faheem Avatar asked Mar 01 '26 15:03

Faheem


1 Answers

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.

like image 144
BalusC Avatar answered Mar 04 '26 06:03

BalusC



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!