Win a copy of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) this week in the OCAJP forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

About Thread

 
Sujittt Tripathyrr
Ranch Hand
Posts: 96
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 210
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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 ]
 
Sujittt Tripathyrr
Ranch Hand
Posts: 96
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 107
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 643
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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();

}
}
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic