File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Confused for threading ? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Confused for threading ?" Watch "Confused for threading ?" New topic
Author

Confused for threading ?

chetan dhumane
Ranch Hand

Joined: Jan 07, 2009
Posts: 629


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://www.androcid.com/
Vijitha Kumara
Bartender

Joined: Mar 24, 2008
Posts: 3775

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.


SCJP 5 | SCWCD 5
[How to ask questions] [Twitter]
Parashuram Hallur
Ranch Hand

Joined: Sep 18, 2006
Posts: 41
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
Posts: 629

Thanks
Then how that synch block will help me.
Parashuram Hallur
Ranch Hand

Joined: Sep 18, 2006
Posts: 41
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
Posts: 629

Thanks
Jain Jose
Greenhorn

Joined: Mar 03, 2008
Posts: 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
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Confused for threading ?
 
Similar Threads
mock exam query
doubt in casting
Doubt in Threads Synchronization
Thread doubt
here is a question and i have a very similar code but i need to convert it