File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
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


Win a copy of EJB 3 in Action this week in the EJB and other Java EE Technologies forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Trouble with synchronized keyword" Watch "Trouble with synchronized keyword" New topic
Author

Trouble with synchronized keyword

Varun Gokulnath
Greenhorn

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

Joined: Apr 06, 2010
Posts: 4240
    
    7

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
Greenhorn

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

Joined: May 22, 2011
Posts: 7
Thanks Udara. Your help is much appriciated.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Trouble with synchronized keyword
 
Similar Threads
synchronizing a block of code
Synchronized block of code
about synchronizing
Doubt in exercise 9-2,K&B -Threads
threads ... from K&B