0

while debugging result is 77777 otherwise 97777. Same behavior if we move System.out.println(Thread.currentThread().getName()); up and below while printing the co.code. any explanation?

public class Concepts extends Thread {
int code = 9;

public void run() {
    this.code = 7;
}

public static void main(String[] args) {

    Concepts co = new Concepts();
    co.start();
    for (int i = 0; i < 5; i++) {
        System.out.print(co.code + "==");
        System.out.println(Thread.currentThread().getName());
    }
  }
}

1 Answers1

1

You are executing a second thread that sets the code instance variable to 7 without any synchronization.

And you access the code variable from your main thread, again without any synchronization.

This means that the main thread may see the state of the code variable prior to the other thread setting it to 7 (which means it would print 9 until it observes the change made by the other thread), or it may not (which means it would only print 7s). It all depends on which thread will run first.

Without synchronization you have no reason to expect one outcome over the other.

Eran
  • 387,369
  • 54
  • 702
  • 768