Yes the synchronized blocks will synchronize on the String "x" from the pool. Do you have some doubts about the output?? Here run2 is called from a synchronized block, so the thread already holds the lock on the desired object when run2 is called...
line 3 is causes the method to be synchronized on the object "x"
this means that no other thread can access the synchronized code till the lock is acquired
now in that method
we call the run2() method
and this method is also synchronized on the object "x"
now when t1 or t2 is started
only one of the thread will run the synchronized code
and also the method called from the synchronized block is synchronized on the same object "x" (due to the String literal pool)
hence the method run2 can be accessed by the object of which lock the thread has acquired and it can call run2 through run method
the output should contain X and then X2 for any order of the threads that are started and start executing
SCJP 6 [86%], OCPWCD [84%], OCEJPAD [83%]
If you find any post useful, click the "plus one" sign on the right
Won't you be my neighbor? - Fred Rogers. tiny ad:
Free, earth friendly heat - from the CodeRanch trailboss