I have this code which has a synchronized run method.
I want to know that the run method is synchronized on which object?
And if it is synchronized on 'u',then why does the output is not continuous,i.e why does it comes like this-"Thread-0 Thread-0 Thread-0 Thread-1 Thread-2..."?
Please help me out .
In your example the run method will synchronize of the UseThreads object i.e. u object. The output is correct IMO. You get the name of the same thread 3 times. The order cannot be guaranteed as one thread completes, which thread will get lock on the object is decided by the JVM not by us (unless you use wait-notify to notify a particular thread)...
Yes Ankit,I do agree by what you say,'
But isn't it correct that as the run method is synchronized,the threads will have a lock on 'u' object,and hence other thread cannot execute the same method run,when the lock on the object is held by some other thread?
When you start multiple threads simultaneously you should keep one thing in mind that, output will not be same every time you run the code.
If your run method is synchronized then any of the 4 thread name can be printed anytime, but it will be printed thrice consecutively as when one thread have lock on run method other can not enter it(which thread will gain the lock is unpredictable as it is not necessary that if a thread is started first mean it will gain the lock early), i.e -