The moose likes Beginning Java and the fly likes Trouble with synchronized keyword Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Trouble with synchronized keyword" Watch "Trouble with synchronized keyword" New topic

Trouble with synchronized keyword

Varun Gokulnath

Joined: May 22, 2011
Posts: 13
Hi everyone,
I am preparing for the SCJP test 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.

Matthew Brown

Joined: Apr 06, 2010
Posts: 4543

Hi Varun. Welcome to The Ranch!

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?
Varun Gokulnath

Joined: May 22, 2011
Posts: 13
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.

Udara Amarasinghe
Ranch Hand

Joined: Aug 17, 2009
Posts: 109

Hi Varun,

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.

Here is one and easy way. Study it.
Varun Gokulnath

Joined: May 22, 2011
Posts: 13
Thanks Udara. Your help is much appriciated.
I agree. Here's the link:
subject: Trouble with synchronized keyword
jQuery in Action, 3rd edition