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 thread question Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of The Java EE 7 Tutorial Volume 1 or Volume 2 this week in the Java EE forum
or jQuery UI in Action in the JavaScript forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "thread question" Watch "thread question" New topic
Author

thread question

Santosh Bapat
Greenhorn

Joined: Mar 13, 2002
Posts: 7
Hi all. This is my first post although I have been sucking information from this site for quite a while now. Can anyone tell me why the following program prints the numbers 0-9 in a random order regardless of whether or not the run() method is synchronized. As (I thought) I understood it, synchronized will only give one Thread object access to the method at a time. I would think that if I used "synchronized" the numbers 0-9 would be printed out in order 4 times. Thanks in advance for your help

public class tosh extends Thread
{
static Thread t1=new tosh();
static Thread t2=new tosh();
static Thread t3=new tosh();
static Thread t4=new tosh();
public static void main(String [] args)
{

t1.start();
t2.start();
t3.start();
t4.start();
}
public synchronized void run()
{
for (i=0;i<10;i++)
{
System.out.println(i);}
}
}


A sincere thanks to all those who take the time to help others.
Dave Vick
Ranch Hand

Joined: May 10, 2001
Posts: 3244
Santosh
Keep in mind that in the code you posted the synchronized keyword will synchronize the method on the current(calling) object. In other words once t1 is in the run method no other code that is synchronized on t1 can execute until the run method exits.
However, in your example you are creating 4 different objects each of which have their run method synchronized on themselves. So the run methods do get locked but the other objects are not calling the run method with the same object they are calling the run methods on themselves.
Here is you code modified to show you how to go about locking the run method - you ahve to do it with a common object that can be used by each of the new threads you create.

hope that helps
[ March 26, 2002: Message edited by: Dave Vick ]

Dave
Santosh Bapat
Greenhorn

Joined: Mar 13, 2002
Posts: 7
Thanks Dave. That makes sense.
Arun Pai
Ranch Hand

Joined: Mar 11, 2002
Posts: 143
Santosh , Your code does not compile . please initialize int i before for loop.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: thread question