System.out.println("Main Thread Ended"); System.out.println("-----------------"); } } In above program there are 5 instances of Test1 (extends Thread) class. All 5 threads are accessing Static method name display.
Now my question is that �do all threads (t1, t2, t3, t4, t5) in above program shares single copy of static display method�.
My another question is that �if I replace code shown below with code in main in above program The result will be still same�.
1) Yes. 2) The result will be "similar", not same.
In the first version, you are explicitly setting the names. In the second version, the names will be given automatically.
In the first version you are running five threads from main, in the second version you are running four.
As far as the output it is guaranteed that once a thread starts executing "display" method, no other thread can start it unless the first finishes. However, the relative ordering between the threads will still be at the JVM's discretion.
Also, there is a "main thread" which is printing "Main Thread Ended" and "-----------------" . This is independent of the display method, and so these two statements will be interwoven with the output in the random manner.
Essentially, the static method 'display' will still be shared and since the static method is synchronized, only one thread will be able to execute it at a time.
Another question for new Java learners (profis, please resist...):
When we are dealing with a static method, what object gets locked in order to achieve synchronization? How does the JVM know not to let other threads access synchronized static methods (in this case, the display() method.)? [ July 21, 2006: Message edited by: Douglas Chorpita ]
SCJP 1.4 - 95%
You ridiculous clown, did you think you could get away with it? This is my favorite tiny ad!