This week's book giveaway is in the OCPJP forum. We're giving away four copies of OCA/OCP Java SE 7 Programmer I & II Study Guide and have Kathy Sierra & Bert Bates on-line! See this thread for details.
I have a doubt in the program. Here in the line # 1,2,3 there are 3 different objects. the synchronized block locks the currently running object instance variable string buffer sb. Each object has it's own copy of instance variable sb. According to me, the lock is not unique to the class. In that case, there will be a race condition among three threads. But, how it is preventing the threads from running simultaneously.
Each object has it's own copy of instance variable sb. According to me, the lock is not unique to the class. In that case, there will be a race condition among three threads. But, how it is preventing the threads from running simultaneously.
Take a look at your code again. Each object has an sb reference, which is assigned in the constructor. All three objects are called using the same string buffer object (passed in the constructor), hence, all three objects refers to the same sb object.
Originally posted by Ganeshkumar cheekati: i think three different objects are created in line 1,2,3. can anyone give more explanation?
Here goes. Your a correct that three objects of the class InSync are instantiated. As this class extends Thread calling the start method creates three threads of execution. In the constructor call the InSync objects are passed the reference to single instance of the StringBuffer class. That is the three instances of InSync have a reference to the same StringBuffer object.
You might visualise this as follows (where [:InSync] representes the three anonymous, not named, instances of the InSync class and [sb:StringBuffer] representes the single instance of StringBuffer):
When each thread is executed it's run method acquires the lock of the object [sb:StringBuffer]. As there is only one StringBuffer object each thread executes the code in the run method sequentially.