| Author |
Confused for threading ?
|
chetan dhumane
Ranch Hand
Joined: Jan 07, 2009
Posts: 628
|
|
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: 3670
|
|
|
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: 628
|
|
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: 628
|
|
|
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
|
 |
 |
|
|
subject: Confused for threading ?
|
|
|