Java Program Output - Simultaneous

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.

+3
source share
2 answers

can the output of this program (as it is) be zero?

Yes it is possible. The code does not guarantee that it t1will end before completion t2. If this is your intention, you may find it CountdownLatchor CyclicBarrieruseful. Click links, their javadocs contains code examples.


, AtomicInteger runnables , .

+5

, 1:

public void run(){
    int x = 1;

    if(Test2.c.b.get() == 1)
        x = Test2.c.a;

    System.out.println("Value of x = "+x);
}

- /:

  • x 1
  • , x, Test2.c.a
  • Test2.c.a x, 1 Test2.c.b
  • 1 Test2.c.b 1 Test2.c.a
  • Test2.c.b , , , (volatile not) , Test2.c.b. , t2 1 Test2.c.a
  • (.. Test2.c.b -, 1), x 1, 1.

, , , 0 x .

+1

Source: https://habr.com/ru/post/1759656/


All Articles