I would like to know if the output would be "XYZ" as well.
In this code seems that the method Tread.sleep(1000) only is considered for the main thread.
Why not for the td thread?
Because then td thread would sleep, main thread would set the variable to "XYZ" , td would wake up and it would print "XYZ".
When your run the program ,then a thread called as main thread which execute main method is present. So when you do Thread.sleep() it will make the thread to sleep in which it is running ( which is main thread). So your main thread goes to sleep and thread td prints the output as 'ABC'
In this code seems that the method Thread.sleep(1000) only is considered for the main thread.
Why not for the td thread?
Hi
Thread.sleep(long milliseconds) is a static method and can only be called on the current thread means thread which is running.In your code when sleep is called the current thread is main.
Above line will spawn a thread which will get runnable state and eventually the running state.Thread when ever run by JVM will start executing the run method.
If there is a sleep method called in run method or any method called from run method then other thread td will go in sleep state.
Stephen Davies wrote:Obviously if you want your own Thread instance (td) to sleep just call td.sleep(milis)!
That's not true, and that's why many people think that that syntax to call a static method is misleading and it lends itself to mistakes like this. If you call td.sleep(milis) inside main() that will only cause main() to sleep, not td. You need to call the static method from the code of the thread you want to sleep, that's the way sleep() works.
All code in my posts, unless a source is explicitly mentioned, is my own.