Here is my code:
class Question extends Thread {
static String info;
public Question(String info ) {
this.info = info;
}
private void inProtected () {
synchronized ( info ) {
System.out.println("--> " + info + " Hi");
System.out.println("<-- " + info + " Hi");
}
}
public void run () {
inProtected();
}
public static void main (String args []) {
new Question("a").start();
try {
sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
new Question("ab").start();
}
}
This code produces sometimes, an output like this:
--> ab Hi
--> a Hi //Wait a second, what? How can "a" print after "ab"?
<-- ab Hi
<-- ab Hi
I've looked at the code of System.out and several answers on StackOverflow and I know for a fact that System.out is thread safe. Then, how is this execution order possible, given info
is static, and the main thread creates the two threads (with "a" and "ab") in order?
Edit: I am perfectly aware that the method inProtected is not synchronized since the value is changed by the different threads. My question is, how is it possible that "a" prints after "ab", since the main thread creates the threads in order, which consequently modify the static variable info?