posted 12 years ago
Hi, i added logs to your code so it's easier to see whats happening.
The output I get is:
x now is 5
Calling join on Thread-0 from main
Starting thread: Thread-0
Thread-0 is going to sleep for 10 seconds.
Thread-0 has finished sleeping for 10 seconds.
main can continue working.
9
So you can see that:
You have 2 threads working: "Thread-0" created by your call to "new MyThread()" and "main" created by the JVM.
The call to setAndPrintX() is running on "main" as you can see by calling Thread.currentThread().getName() inside the method.
Calling join() inside setAndPrintX() is the same as calling this.join() so join() is called on the anonymous instance of MyThread created in "main" by "new MyThread()".
So in effect the call to join() can be read as:
"main" will wait for "Thread-0" to finish, and then it will continue.
Rodrigo