File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
Win a copy of Soft Skills: The software developer's life manual this week in the Jobs Discussion forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Doubt in Threads Synchronization

 
Balaji Bang
Ranch Hand
Posts: 182
Java
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator



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
Posts: 210
Eclipse IDE Java Linux
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Ganeshkumar cheekati
Ranch Hand
Posts: 362
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
hi banu
please use code tags
 
Balaji Bang
Ranch Hand
Posts: 182
Java
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic