• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Confused for threading ?

 
chetan dhumane
Ranch Hand
Posts: 641
Android Eclipse IDE Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

Even if i synchronized the method outputn is different

aa: 0
bb: 0
aa: 1
bb: 1
aa: 2
bb: 2
cc: 0
cc: 1
cc: 2
cc: 3
cc: 4
cc: 5
cc: 6
cc: 7
cc: 8
cc: 9
aa: 3
bb: 3
bb: 4
bb: 5
aa: 4
bb: 6
aa: 5
bb: 7
aa: 6
bb: 8
aa: 7
bb: 9
aa: 8
aa: 9
 
Vijitha Kumara
Bartender
Posts: 3913
9
Chrome Fedora Hibernate
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
These (Thread a,b & c) are three different threads. When you start them they will run in any order (which JVM will decide). Making run method synchronize won't help. When you start those threads they will run their own run methods (which are from three different ThreadBob objects) , each of those have no relation with other's.
 
Parashuram Hallur
Ranch Hand
Posts: 41
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Chetan,

If you are expecting each of the threads to be run sequentially, then the code should be modified as below. Lines 9 - 11.



Since you have created three instances of ThreadBob, they wont interfere each other.

HTH
 
chetan dhumane
Ranch Hand
Posts: 641
Android Eclipse IDE Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks
Then how that synch block will help me.
 
Parashuram Hallur
Ranch Hand
Posts: 41
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
chetan dhumane wrote:Thanks
Then how that synch block will help me.


Modifying the code as I suggested will make use of the synchronized and will run sequentially. Otherwise it is not guaranteed to run in a sequence. Please note that if you are synchronizing, in other words acquiring lock, make sure it is on the single object. Otherwise it really does not make sense.
 
chetan dhumane
Ranch Hand
Posts: 641
Android Eclipse IDE Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks
 
Jain Jose
Greenhorn
Posts: 3
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Chetan

You may be looking for an answer on how synchronized work in run() method. the following discussion will be useful

Thread with synchronized run() method
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic