GeeCON Prague 2014*
The moose likes Beginning Java and the fly likes about thread synchronization Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


JavaRanch » Java Forums » Java » Beginning Java
Bookmark "about thread synchronization" Watch "about thread synchronization" New topic
Author

about thread synchronization

sharma sachin
Greenhorn

Joined: Nov 13, 2009
Posts: 24
hello friends

i am not understanding the output of the above program
as i have declared fname() method as synchronized so accrding to me output will be
0,1,2,3,4 for thread1
and 0,1,2,3,4 for thread2
or else i am doing mistake in my code can you explain that how we can achieve the desired output for different threads with the help of suitable example
Seetharaman Venkatasamy
Ranch Hand

Joined: Jan 28, 2008
Posts: 5575

If I understood your question, you need to create one object and start two threads *on that one object* .
so, change

to

and observe the output!
Jesper de Jong
Java Cowboy
Saloon Keeper

Joined: Aug 16, 2005
Posts: 14194
    
  20

Yes, you have declared the method to be synchronized, but you have two threads that are using two different MyThread objects.

The first one will synchronize on the first MyThread object, and the second one on the second MyThread object. Since these are separate objects, the two threads will not wait for each other. Synchronizing will make threads wait only if you let both threads synchronize on a shared object. Like this:


Java Beginners FAQ - JavaRanch SCJP FAQ - The Java Tutorial - Java SE 8 API documentation
sharma sachin
Greenhorn

Joined: Nov 13, 2009
Posts: 24
thanks a lot jesper
can you also please tell me that how can we print first name and last name using two different threads on shared object
Sandeep Kumar B
Ranch Hand

Joined: Jul 10, 2011
Posts: 41
Sachin
This should help
Feel free to ask any other question you have

 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: about thread synchronization