File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Trouble with synchronized keyword

 
Varun Gokulnath
Greenhorn
Posts: 13
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 4549
8
Java Netbeans IDE Scala
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 13
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 109
Java Netbeans IDE Oracle
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 13
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks Udara. Your help is much appriciated.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic