I am preparing for the SCJPtest and I have trouble understanding the usage of the synchronized keyword. In the following code i am attempting to create three threads and synchronize the run method such that 100 As Bs and Cs will be printed unbroken on one line. But the trouble is that the output is getting all jumbled up. Am I right in thinking that since the run method is synchronized, once a thread has entered it, no other thread can enter until the first thread had exited the method. Can anyone please tell me where I'm going wrong.
Thanks in advance.
Two threads that are synchronized on the same object cannot run the method at the same time. So the question is, what object are the threads synchronized on?
Joined: May 22, 2011
Thanks Matthew. I rewrote the above code as follows. I have synchronized on any instance of the StringBuffer class so that the threads can lock onto instances of the StringBuffer which they all use. Now the program prints unbroken lines of As,Bs and Cs but the order in which they are printed is not fixed. How can I fix it such that As,Bs and Cs are printed in order.
By adding synchronized keyword to run method its synchronize that InSync thread objects run method only. So that's not effect on other InSync thread objects. But it will effect if some threads invoke one specific InSync instance run method just as simple method invocation.
There are three ways to make this code work correctly.