This week's book giveaway is in the OCPJP forum.
We're giving away four copies of OCA/OCP Java SE 7 Programmer I & II Study Guide and have Kathy Sierra & Bert Bates on-line!
See this thread for details.
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Doubt in Threads Synchronization Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of OCA/OCP Java SE 7 Programmer I & II Study Guide this week in the OCPJP forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Doubt in Threads Synchronization" Watch "Doubt in Threads Synchronization" New topic
Author

Doubt in Threads Synchronization

Balaji Bang
Ranch Hand

Joined: Apr 23, 2007
Posts: 180



For this I got the output as :
Thread-0 0
Thread-1 0
Thread-0 1
Thread-1 1
Thread-0 2
Thread-1 2
Thread-0 3
Thread-1 3
Thread-0 4
Thread-1 4
Thread-0 5
Thread-1 5
Thread-0 6
Thread-1 6
Thread-0 7
Thread-1 7
Thread-0 8
Thread-1 8
Thread-0 9
Thread-1 9

My Doubt is : when the first Thread 's' has been started in gets the lock on the getTotal synchronized method. Then no other Thread can enter that method. but why the output is showing a mix of both Threads??
But if I run the same codeby implementing Runnable then Then Thread 1 is running after the Thread 0 has been completed.

What is the difference ???
ramesh maredu
Ranch Hand

Joined: Mar 15, 2008
Posts: 210

Output is mixed because you are executing two threads which are created from two different objects so synchronization can not be achieved.

Post your code with Runnable interface, if code is same like above (creating two objects) it also should not give expected output.


SCJP 1.5 94%.
The greatest glory in living lies not in never falling, but in rising every time we fall.
Ganeshkumar cheekati
Ranch Hand

Joined: Oct 13, 2008
Posts: 362
hi banu
please use code tags


SCJP5 and SCWCD1.5
Think Twice Act Wise...
Balaji Bang
Ranch Hand

Joined: Apr 23, 2007
Posts: 180
Yes you are right. I made a mistake by passing same runnable target to both threads.



Here t and t1 are having same Runnable target. If so then we will get Thread1 runs after Thread0 has completed? If we have two threads running on different objects we will get a mix.
Synchronization means only one thread( on single object) can access the method at a time.
how can we create two threads on same object when we are extending a Thread class.
 
jQuery in Action, 2nd edition
 
subject: Doubt in Threads Synchronization