[Logo] JavaRanch » JavaRanch Saloon
  Search | FAQ | Recent Topics | Hot Topics
Register / Login


Win a copy of Flex 4 in Action this week in the Flex forum!
Reply Bookmark it! Watch this topic JavaRanch » Forums » Professional Certification » Programmer Certification (SCJP)
 
RSS feed
 
New topic
Author

Confused for threading ?

chetan dhumane
Ranch Hand

Joined: Jan 07, 2009
Messages: 385


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

http://techfreak.byteicon.com
- Cool gadgets to hang out with.

Vijitha Kumara
Ranch Hand

Joined: Mar 24, 2008
Messages: 1988

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.

This message was edited 1 time. Last update was at by Vijitha Kumara


SCJP 5, SCWCD 5
Parashuram Hallur
Ranch Hand

Joined: Sep 18, 2006
Messages: 40

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

Joined: Jan 07, 2009
Messages: 385

Thanks
Then how that synch block will help me.

http://techfreak.byteicon.com
- Cool gadgets to hang out with.

Parashuram Hallur
Ranch Hand

Joined: Sep 18, 2006
Messages: 40

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

Joined: Jan 07, 2009
Messages: 385

Thanks

http://techfreak.byteicon.com
- Cool gadgets to hang out with.

Jain Jose
Greenhorn

Joined: Mar 03, 2008
Messages: 3

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
 
jQuery in Action
 
 
Reply Bookmark it! Watch this topic JavaRanch » Forums » Professional Certification » Programmer Certification (SCJP)
 
RSS feed
 
New topic
hibernate profiler