aspose file tools*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes About Thread Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "About Thread" Watch "About Thread" New topic
Author

About Thread

Sujittt Tripathyrr
Ranch Hand

Joined: Jun 21, 2006
Posts: 96
public class Thread_Example1 extends Thread
{

int var;
synchronized public void run()
{
for(var=0;var<10;var++)
{
System.out.println(var);
}
}

public static void main(String s[])
{
Thread_Example1 t1=new Thread_Example1();
Thread_Example1 t2=new Thread_Example1();
Thread_Example1 t3=new Thread_Example1();
t1.start();
t2.start();
t3.start();

}

}

After executing this program still the values are printing randomly. I am using the synchronized but still it is displaying randomly.
why it is displaying like this?
Aum Tao
Ranch Hand

Joined: Feb 14, 2006
Posts: 210
The reason why you are getting random vaues is because each thread you created is operating on a different object. If you want to get the values in order, you should implement Runnable and create threads using this same instance of class implementing this runnable as follows:




[ July 20, 2006: Message edited by: Aum Tao ]
[ July 20, 2006: Message edited by: Aum Tao ]

SCJP 1.4 85%
Sujittt Tripathyrr
Ranch Hand

Joined: Jun 21, 2006
Posts: 96
Thanks very much Aum Tao

I got but still small is there that in extends Thread it is calling the same run method of the class and how the synchronized allow to mutiple threads to execute.

Thakns
Neelesh Bodas
Ranch Hand

Joined: Jul 20, 2006
Posts: 107
Though it is the "same" run method, the "this" reference on which 'run' method runs is different in the three cases. Note that your run method is synchronized on "this" reference (in other words, it requires a lock on 'this' reference before it can run.) Recall that synchronized instance methods will block each other only if they are running on the same instance. In the current case, since the instances are different, different locks are required, and hence they would not block each other.

[As an aside, thats not the case with the static synchronized methods.]
Gowher Naik
Ranch Hand

Joined: Feb 07, 2005
Posts: 643
If u want required output run this code.

public class Thread_Example1 extends Thread
{
int var;
public void run(){
synchronized(Thread_Example1.class){
for(var=0;var<10;var++){
System.out.println(var);
}
}
}

public static void main(String s[]){
Thread_Example1 t1=new Thread_Example1();
Thread_Example1 t2=new Thread_Example1();
Thread_Example1 t3=new Thread_Example1();
t1.start();
t2.start();
t3.start();

}
}
 
It is sorta covered in the JavaRanch Style Guide.
 
subject: About Thread