-3

I'm learning about Java and it's quirks. What's going on here?

public class myThread implements Runnable {

    String msg = "yes";

    public void run() {
        this.msg = "No";
    }

    public static void main(String[] args) {
        myThread one = new myThread();
        (new Thread(one)).start();

        for (int i = 0; i < 10; i++) {
            System.out.println(one.msg);
        }
    }
}

Result: yes No No No No No No No No No

Why does the FIRST result return as 'yes', then it set it to 'No'?

expoter
  • 1,622
  • 17
  • 34
Jeremy
  • 11
  • 3
  • 1
    Does it change when you go from `println` to `print` (so that the buffer will not be flushed and I/O is deferred)? – Thilo Jun 24 '16 at 03:51

3 Answers3

3

Because start() took slightly more time to begin your new thread and modify msg, one loop iteration completed before the thread began. After the first iteration, the msg has been modified by the thread and No is displayed.

Elliott Frisch
  • 198,278
  • 20
  • 158
  • 249
3

Your new thread runs in the background while the main thread continues.

There is no synchronization between the two, so the background thread will change the value from "yes" to "no" at one point that is completely unspecified. In the mean-time, the main thread just prints what it sees at this point in time.

If I understand the Java Memory Model correctly, in the absence of any synchronized, volatile or other synchronization constructs, it is not even guaranteed that the main thread sees the other thread's changes at all.

Thilo
  • 257,207
  • 101
  • 511
  • 656
0

You have created a new Thread and called start() method to start it's execution. But JVM decides when the thread will be run. Everytime you run the program you will get the different result.

First you get yes then No. Main thread first printed yes then JVM started child thread which changed the value of the msg and then control came back to main thread and it printed msg as No till the end of the loop.

Nakul Kumar
  • 170
  • 2
  • 11
  • 2
    "Everytime you run the program you will get the different result." - This is not true. I ran it 100x, and it returned the same result every time. – Jeremy Jun 25 '16 at 20:04